Aloha! I will show you how to make your life easier and your code cleaner when you’re working with Laravel validation rules. Let’s say you have a form to store a new contact in your database. In ContactController you add validation rules like this:
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|max:100',
'email' => 'required|email|max:255|unique:contacts',
]);
Contact::create($request->only(['name','email']));
Session::flash('message', 'Contact was created successfully!');
return back();
}
If form fields won’t be valid then all code execution will be stopped after the $request->validate() method call and then the user will be redirected back to the form page. Let’s do the same thing with Laravel form requests. Run the Artisan command to create a request:
php artisan make:request ContactRequest
This command will create a ContactRequest.php file in the app/Http/Requests directory. Open this file and add your validation rules to the rules() method:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ContactRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|max:100',
'email' => 'required|email|max:255|unique:contacts',
];
}
}
In authorize() method you should change return false to return true. If you need to authorize a user to do this request then here you should add your authorization logic.
public function authorize()
{
return true;
}
The next thing you need to do is open ContactController and type-hint ContactRequest instead of Request in your store() method:
public function store(ContactRequest $request)
And remove these validation rules from the store() method:
$validated = $request->validate([
'name' => 'required|max:100',
'email' => 'required|email|max:255|unique:contacts',
]);
The store() method should look like this:
public function store(ContactRequest $request)
{
Contact::create($request->only(['name','email']));
Session::flash('message', 'Contact was created successfully!');
return back();
}
Laravel form requests code examples
You can find code examples from this article in our GitHub repository.