This request stub is to demonstrate how it is possible to share a single form request for the same model, to store and to update the model.
- If you are using Laravel 7, you can now override default stubs:
php artisan stub:publish
-
Replace the below
request.stub
content with yours atstubs/request.stub
-
Create a request like you normally would, for example:
php artisan make:request Admin/UserRequest
In this form request you can manipulate your data, before and after validation takes place, before returning it to your controller to avoid clutter in your controllers.
Store:
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\Admin\UserRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(UserRequest $request)
{
$user = User::create($request->validated());
// user stored
return redirect()->route('admin.users.show', $user);
}
Update:
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\Admin\UserRequest $request
* @param \App\User $user
* @return \Illuminate\Http\RedirectResponse
*/
public function update(UserRequest $request, User $user)
{
$user->update($request->validated());
// user updated
return redirect()->route('admin.users.show', $user);
}
For this to work, you would need to spoof your form method to PUT when editing your model:
edit.blade.php:
<form method="POST" action="{{ route('admin.users.update', $user) }}">
@csrf
@method('PUT')
<input type="hidden" name="model_id" value="{{ $user->id }}">
...
</form>
Please comment if you have suggestions or better solutions, then I'll update my post. Thanks! 😎