Table of Contents
In the previous form validation in laravel 6 tutorial, we have seen how to validation form request data, display error messages and change error massage placement in blade file.
Now in this tutorial, i will show you how to validate form data using laravel form requests which is considered best method to form validation.
Why we require form request validation? Let me explain this. Suppose we have so many fields in form and need to validate them. Also need to customize some validation rules as well. If we write all validation in controller method then it looks bad and long. Better we make separate validation class and write all the validation rules and customize them.
Form requests are custom request classes that contain validation logic. It gives more flexibility compared with request validation shows in previous tutorial. I personally recommend to use form request validation in laravel.
Lets start step by step and learn form data validation using form requests in laravel 6.
Here i will use same customer form example which we used in previous tutorial. Let me show you previous controller file and what i am going to change in it.
CustomerController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class CustomerController extends Controller { /** * Create add customer form */ public function create() { return view('customer.add'); } /** * Create add customer form data */ public function store(Request $request) { $validatedData = $request->validate([ 'firstname' => 'required|max:255', 'lastname' => 'required|max:255', 'email' => 'required|unique:customers|max:50', 'telephone' => 'required', 'birthdate' => 'required' ]); // Store validate data in database } }
Create Form Request
Lets create customer form request using below artisan command.
php artisan make:request CustomerRequest
Above command will generate CustomerRequest.php under app/Http/Requests folder. Open it and add validation rules as shown below.
CustomerRequest.php
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class CustomerRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'firstname' => 'required|max:255', 'lastname' => 'required|max:255', 'email' => 'required|unique:customers|max:50', 'telephone' => 'required', 'birthdate' => 'required' ]; } }
I have added validation rules for all form fields. Form data successfully submit if only form validation become successful.
In the above form request, there in authorize
method. Within this method, you may check if the authenticated user actually has the authority to update a given resource.
If you don’t want to write any authorization logic then simply return true
will do job. If the authorize
method returns false
, a HTTP response with a 403 status code will automatically be returned and your controller method will not execute.
Add Form Request In Controller
After writing all validation logic in form request, its time to use it in controller. Lets import CustomerRequest into CustomerController as shown below.
CustomerController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests\CustomerRequest; class CustomerController extends Controller { /** * Create add customer form */ public function create() { return view('customer.add'); } /** * Create add customer form data */ public function store(CustomerRequest $request) { // Get validated form data $requestData = $request->validated(); // Store data into database } }
Have you notice that i have remove all the validation logic from store method and define CustomerRequest form request. Now form data will be validated from CustomerRequest and if validation successful then we can retrieve validated form data using $request->validated() method. You can do further process on validated data.
If validation fails, it display appropriate errors on customer form shown as below.
Customize Validation Error Message
We can customize validation error message from CustomerRequest form request.
CustomerRequest.php
/** * Get the error messages for the defined validation rules. * * @return array */ public function messages() { return [ 'firstname.required' => 'Firstname is required', 'lastname.required' => 'Lastname is required', 'email.required' => 'Email is required', 'email.unique' => 'Email should be unique', 'telephone.required' => 'Telephone is required', 'birthdate.required' => 'Birthdate is required', ]; }
You can customize validation error message as shown above. It will look like below.
Adding After Hooks To Form Requests
If you would like to add an “after” hook to a form request, you may use the withValidator
method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:
/** * Configure the validator instance. * * @param \Illuminate\Validation\Validator $validator * @return void */ public function withValidator($validator) { $validator->after(function ($validator) { if ($this->somethingElseIsInvalid()) { $validator->errors()->add('field', 'Something is wrong with this field!'); } }); }
You can check whatever validation logic using withValidator
method. For example, if you want to keep product id unique for customer in the cart then you can use withValidator
method. There are so many logic where you need to use this method for extend validation scenario.
I hope that you may like Form data validation using form requests in laravel 6 tutorial. Please share with your friends and let me know if you don’t get any part of this tutorial. Happy Coding 🙂