因此,我在我的控制器中有一個創建功能,如下所示,我的路線是這樣的,我的問題是有沒有辦法讓我在不同的創建和編輯條件相同的功能都具有相當類似的編碼。有人能啓發我嗎?在同一個控制器中創建編輯功能laravel
class ManageAccountsController extends Controller
{
public function index() {
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function update()
{
// process the form here
// create the validation rules ------------------------
$rules = array(
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the user table
'password' => 'required|min:8|alpha_num',
'password_confirm' => 'required|same:password', // required and has to match the password field
'mobile' => 'required',
'role_id' => 'required'
);
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(Input::all(), $rules);
// check if the validator failed -----------------------
if ($validator->fails()) {
// redirect our user back to the form with the errors from the validator
$input = Input::except('password', 'password_confirm');
$input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
return redirect()
->back()
->withInput($input)
->withErrors($validator);
} else {
// validation successful ---------------------------
// user has passed all tests!
// let user enter the database
// create the data for our 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 our user
$user->save();
// redirect ----------------------------------------
// redirect our user back to the form so they can do it all over again
Session::flash('flash_message', 'User successfully added!');
return redirect()->back();
}
}
}
routes.php文件
Route::get('manage_accounts', '[email protected]');
Route::post('manage_accounts', '[email protected]');
首先,非常感謝。代碼似乎更有條理。 Mange讓我的創建操作工作,現在我想知道如何調用更新操作。在我的路線中,我指定 Route :: post('manage_accounts','ManageAccountsController @ register'); 用於調用create方法,abt如何更新?我可以在寄存器路由之後像這樣指定它: Route :: post('manage_accounts','ManageAccountsController @ update'); – EunJi
你還在上面寫了UpdateUserRequest $ request,這是否意味着我必須爲更新創建另一個驗證請求文件?所以如果有一個刪除方法,由於驗證我是差異,我會創建另一個請求文件,我是嗎? – EunJi
好問題。所以,我在這裏錯過了一些東西,但已經編輯了這篇文章,以使這一切更加完整。你可以很好地利用Laravel的'寧靜的資源控制器'來整理你的路線,讓你思考和編碼RESTfully(好習慣) 想想你的索引方法中的代碼添加到存儲庫 - 那麼你的控制器可以完成它的工作作爲調解人,而不必處理稍後可能想要重複使用的邏輯。 – browno