如何指定使用(存储和更新)laravel 的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33461869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:36:32  来源:igfitidea点击:

How to specify which method to use (store and update) laravel

phplaravelmodal-dialog

提问by EunJi

So basically I have a store function and update function in my controller.php and was wondering how do I specify which method to used when needed. My progress of code is as shown below. Anyone has a solution for this?

所以基本上我在我的 controller.php 中有一个 store 函数和 update 函数,并且想知道如何指定在需要时使用哪种方法。我的代码进度如下所示。任何人都有解决方案?

routes.php

路由文件

Route::resource('manage_accounts', 'ManageAccountsController',
                ['only' => ['index', 'store', 'update']]);

view.blade.php

视图.blade.php

 <button class="btn btn-sm btn-warning" type="button"
          data-toggle="modal" data-target="#register" value="{{ $user->id }}">Edit&nbsp;<i class="glyphicon glyphicon-edit"></i></button>
 <button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#register">Register New User</button>

 <!-- Modal -->
    <div id="register" class="modal fade" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
               <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal">&times;</button>
                  <h4 class="modal-title">User Information</h4>
              </div>
              <div class="modal-body">
                  <form class="form-horizontal" role="form" method="POST" action="/manage_accounts" novalidate>
                   <input type="hidden" name="_token" value="{{ csrf_token() }}">
                   <div class="form-group">
                    <label class="control-label col-sm-3" for="name">Username:</label>
                    <div class="col-sm-5 @if ($errors->has('name')) has-error @endif"> 
                       <input type="text" class="form-control" type="hidden" id="name" name="name" placeholder="Enter username">
                       @if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> @endif
                   </div>
               </div>
               <div class="form-group">
                <label class="control-label col-sm-3" for="password">Password:</label>
                <div class="col-sm-5 @if ($errors->has('password')) has-error @endif"> 
                   <input type="password" class="form-control" type="hidden" id="password" name="password" placeholder="Enter login password">
                   @if ($errors->has('password')) <p class="help-block">{{ $errors->first('password') }}</p> @endif
               </div>
           </div>
           <div class="form-group">
            <label class="control-label col-sm-3" for="password_confirm">Confirm Password:</label>
            <div class="col-sm-5 @if ($errors->has('password_confirm')) has-error @endif"> 
               <input type="password" class="form-control" type="hidden" id="password_confirm" name="password_confirm" placeholder="Re-type password again">
               @if ($errors->has('password_confirm')) <p class="help-block">{{ $errors->first('password_confirm') }}</p> @endif
           </div>
       </div>
       <div class="form-group">
        <label class="control-label col-sm-3" for="email">Email:</label>
        <div class="col-sm-5 @if ($errors->has('email')) has-error @endif"> 
           <input type="email" class="form-control" type="hidden" id="email" name="email" placeholder="Enter email address">
           @if ($errors->has('email')) <p class="help-block">{{ $errors->first('email') }}</p> @endif
       </div>
   </div> 
   <div class="form-group">
    <label class="control-label col-sm-3" for="mobile">Phone Number:</label>
    <div class="col-sm-5 @if ($errors->has('mobile')) has-error @endif"> 
       <input type="hpnum" class="form-control" type="hidden" id="mobile" name="mobile" placeholder="Enter handphone number">
       @if ($errors->has('mobile')) <p class="help-block">{{ $errors->first('mobile') }}</p> @endif
   </div>
</div>
<!--<div class="form-group">
    <label class="control-label col-sm-3" for="officeEx">Office Extension:</label>
        <div class="col-sm-5"> 
            <input type="officeEx" class="form-control" id="officeEx" placeholder="Enter office extension">
        </div>
    </div> -->                                                                                                                     
   <div class="form-group">
    <label class="control-label col-sm-3" for="role_id">Role:</label>
    <div class="col-sm-5">
        <select class="form-control" type="hidden" id="role_id" name="role_id">
            @foreach ($roles as $role)
            <option value="{{ $role->id }}">{{ $role->role_description }}</option>
            @endforeach
        </select>
    </div>
</div>
<div class="form-group"> 
    <div class="col-sm-offset-3 col-sm-5">
       <button type="submit" class="btn btn-default">Update</button>
   </div>
</div>
</form>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>

controller.php

控制器.php

class ManageAccountsController extends Controller
{
    public function index() 
    {
        $users = User::orderBy('name')->get();
        $roles = Role::all();

        return view('manage_accounts', compact('users', 'roles'));
    }

    public function store(StoreNewUserRequest $request)
    {
        // create the data for new user
        $user = new User;
        $user->name     = Input::get('name');
        $user->email    = Input::get('email');
        $user->password = Hash::make(Input::get('password'));
        $user->mobile   = Input::get('mobile');
        $user->role_id  = Input::get('role_id');

        // save new user
        $user->save();

        Session::flash('flash_message', 'User successfully added!');

        return redirect()->back();
    }

    public function update($id)
    {
        // update existing user
        $user = User::findOrFail($id);

        $user->name     = Input::get('name');
        $user->email    = Input::get('email');
        $user->password = Hash::make(Input::get('password'));
        $user->mobile   = Input::get('mobile');
        $user->role_id  = Input::get('role_id');

        // save existing user
        $user->save();

    }
}

采纳答案by Jeff Lambert

All resource controllersdo for you is offer a convenient shortcut to the following:

所有资源控制器为您做的都是提供一个方便的快捷方式:

Route::get('/resource',                 ['as' => 'resource.index',      'uses' => 'ResourceController@index'    ]);
Route::get('/resource/create',          ['as' => 'resource.create',     'uses' => 'ResourceController@create'   ]);
Route::post('/resource',                ['as' => 'resource.store',      'uses' => 'ResourceController@store'    ]);
Route::get('/resource/{resource}',      ['as' => 'resource.show',       'uses' => 'ResourceController@show'     ]);
Route::get('/resource/{resource}/edit', ['as' => 'resource.edit',       'uses' => 'ResourceController@edit'     ]);
Route::put('/resource/{resource}',      ['as' => 'resource.update',     'uses' => 'ResourceController@update'   ]);
Route::delete('/resource/{resource}',   ['as' => 'resource.destroy',    'uses' => 'ResourceController@destroy'  ]);

So if you call Route::resource('manage_accounts', 'ManageAccountsController')you are creating 7routes. You're specifically telling Laravel to only create 3 of them, namely these:

因此,如果您致电,Route::resource('manage_accounts', 'ManageAccountsController')您将创建7条路线。你特别告诉 Laravel 只创建其中的 3 个,即:

Route::get('/resource',                 ['as' => 'resource.index',      'uses' => 'ResourceController@index'    ]);
Route::post('/resource',                ['as' => 'resource.store',      'uses' => 'ResourceController@store'    ]);
Route::put('/resource/{resource}',      ['as' => 'resource.update',     'uses' => 'ResourceController@update'   ]);

You call those three methods on your controller by requesting those route URLs, e.g. you would 'call' the index route simply by requesting it's URL:

您可以通过请求这些路由 URL 来调用控制器上的这三个方法,例如,您可以通过请求它的 URL 来“调用”索引路由:

GET http://server/resource

When I look at your markup, I see this form tag:

当我查看你的标记时,我看到了这个表单标签:

<form class="form-horizontal" role="form" method="POST" action="/manage_accounts" novalidate>

This will create this HTTP request when the form is submitted:

这将在提交表单时创建此 HTTP 请求:

POST http://server.com/manage_accounts

Comparing that to your resource routes, this will wind up calling your controller's store()method. If you want that form to call your update()method instead, you must make a PUT request. Since HTML forms can't make PUT requests, Laravel provided a way to mimick a PUT request with forms:

将其与您的资源路由进行比较,这将最终调用您的控制器store()方法。如果您希望该表单调用您的update()方法,则必须发出 PUT 请求。由于 HTML 表单不能发出 PUT 请求,Laravel 提供了一种用表单模拟 PUT 请求的方法:

<form class="form-horizontal" role="form" method="POST" action="/manage_accounts/{{ $account->id }}" novalidate>
    <input type="hidden" name="_method" value="PUT" />

Also notice that the url the form is posting to has changed, and should include the ID of an actual account you want to update.

另请注意,表单发布到的 url 已更改,并且应包含您要更新的实际帐户的 ID。

You may also find it helpful to compare this to what artisan itself sees as your available routes. You can list all of your available routes by issuing the artisan command $ php artisan route:list(Laravel 5) or $ php artisan routes(Laravel 4)

您可能还会发现将其与工匠本身认为的可用路线进行比较会很有帮助。您可以通过发出 artisan 命令$ php artisan route:list(Laravel 5) 或$ php artisan routes(Laravel 4)列出所有可用的路由

回答by Mindau

Use Store methode to create records in database. Update method use to edit records. Like example create method - register user and update method - edit profile

使用 Store 方法在数据库中创建记录。更新方法用于编辑记录。例如创建方法 - 注册用户和更新方法 - 编辑个人资料