In this snippet i will discuss the different ways of using laravel validator and what is the best use case of using each method.
$this->validate()
The first and the simple way of using laravel validator is using $this->validate() function inside any controller action as this method is available through the base Controller class that laravel provides. The function takes two mandatory parameters $request and $rules:
$this->validate($request, $rules);
For example:
public function store(Request $request) { $this->validate($request, [ 'username' => 'required', 'password' => 'required' ]); }
$rules is an array of key value pairs which represent the form fields and the corresponding validations.
To display the error messages in the view laravel will share a special variable called $errors that will be available after you submit the form:
@if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif
Laravel validator uses validation messages that located in resources>lang>{current language}>validation.php by default but if you want to customize the validation messages and attributes in this context only then $this->validate() can accept two other parameters which is the $messages and $customAttributes.
For example:
$this->validate($request, [ 'user_name' => 'required', 'password' => 'required' ], [ 'required' => 'Please fill in the :attribute field' ], [ 'user_name' => 'Username' ] );
As shown above the $messages is an array of rules names as the key and their messages as the value. Also the $customAttributes is an array of fields as the key and the field names as the value.
This way of using the validator can be used only inside controllers. But what if we want to use the validator in some other classes for example the models, in this case we can make use of Validator::make()
Validator::make()
Laravel provides a way to construct a validator object using the Validator::make() method. This method returns a new validator factory that can be used to validate the request in the same way as $this->validate()
use Validator; public function store(Request $request) { $validator = Validator::make($request->all(), [ 'title' => 'required', 'body' => 'required', ]); if ($validator->fails()) { return redirect('create') ->withErrors($validator) ->withInput(); } }
As shown the Validator::make() receives the $request data as the first parameter and the $rules as the second parameter. To send the errors to the view we pass the validator instance as the parameter to withErrors() method which in turn share the $errors variable to the view.
If you are sending form via ajax request you can receive the errors by calling:
$errors = $validator->errors();
Or
To retrieve an array of all messages for all fields, use the all
method:
foreach ($errors->all() as $message) { // }
This method is perfect for small and medium projects. For more clean way of using validator is the Form Request Classes.
Form Request Classes:
Instead of writing the validation logic in the controllers or models, Laravel provides a dedicated classes of writing the validation logic, this provides us with a cleaner code environment that achieves the Single Responsibility Principal and area of responsibility.
To generate the validation class we can use the artisan command:
php artisan make:request PostValidator
This command will create a new folder inside app/ directory called Requests/ inside this folder is the PostValidator class
app>Http>Requests>PostValidator.php
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class PostValidator 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 [ ]; } }
The rules() method must return the array of rules like this:
public function rules() { return [ 'title' => 'required', 'body' => 'required' ]; }
The authorize() method return false by default which means that it’s not authorized to be used by any . Change it to return true or supply your logic to check for example that authenticated users only have access to this validator.
public function authorize() { return true; }
Using Form Request Class in Controller:
To use the form request class in the controller we typehint the class in any controller method that uses validation like this:
public function store(PostValidator $request) { // validate $validated = $request->validated(); }
Calling $request->validated() have the same behavior as $this->validate() we saw previously, and it will send the $errors variable automatically to the view in case validation failure.
Great work man. I was stuck on something for 2 days till I found this. Thanks very much.