Adding validations to any form of web applications is high quality factor. We should always prefer both sides of validations like from client side using javascript or using server side. We can’t trust on user inputs, it results application crash in case of invalid values.
For client side validation using javascript we have an article over it click here to see. Inside this article we will see all Laravel 8 Form validation methods. You can also learn about complete basics of Laravel 8 installation Click here.
Learn More –
- Call MySQL Stored Procedure in Laravel 8 Tutorial
- Chatbot Conversation integration in Laravel 8 Using Botman
- Complete Laravel 8 CRUD Application Tutorial
- Complete Laravel 8 Vue JS CRUD Tutorial
Let’s get started.
Methods of Laravel Form Validation
There are 3 ways to validate form inputs in laravel. We will discuss about each in great detail with complete code snippet and commands. Here, are the following methods –
- Using Laravel validate() method of Request Class
- By Custom Form Request Validation Class
- Creating Manual Validators
Let’s see step by step about each.
Using validate() method of Request Class
To better understand in a very clear we need to create a controller, route, view etc.
Create Controller
$ php artisan make:controller Student
Above command will create a class file at /app/Http/Controllers/Student.php
Open up the file
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Student extends Controller { public function addStudentLayout(){ return view("add-student"); } public function saveStudent(Request $request){ $validatedData = $request->validate([ 'name' => 'required|max:120', 'email' => 'required|unique:students', 'mobile' => 'required|integer|max:10' ]); // The student data is valid... // save data } }
- We have used validate() method of $request which is an instance of Request class.
- Inside validate() method, we have passed an array which contains key and value pairs. Key is the column name and value is form validation rules.
- If any error occurs then it automatically redirects to back route with error messages. If there will no error then we can simply proceed and save data.
Route Configuration
Open the file /routes/web.php
# Import Student Controller Class use App\Http\Controllers\Student; # Routes Route::get("add-student", [Student::class, "addStudentLayout"]); Route::post("submit-student", [Student::class, "saveStudent"]);
- We have created 2 routes. One for showing form layout and other will be for submit form data.
Creating View File
Create a file at /resources/views/add-student.blade.php. Open file
<!DOCTYPE html> <html lang="en"> <head> <title>Laravel 8 Form Validation Methods</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Laravel 8 Form Validation</h2> <!-- display error messages --> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form class="form-horizontal" action="/submit-student"> <div class="form-group"> <label class="control-label col-sm-2" for="name">Name:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="name" placeholder="Enter name" name="name"> <!-- display error for each input --> @error('name') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">Email:</label> <div class="col-sm-10"> <input type="email" class="form-control" id="email" placeholder="Enter email" name="email"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="mobile">Mobile:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="mobile" placeholder="Enter mobile" name="mobile"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </form> </div> </body> </html>
- To display all error message we have used @errors directive & $errors->all() method.
- To display error to each individual input, we have @error directive. $message is a key of error bag to display error.
- Error messages are by default managed by application.
To Change the default error message
public function saveStudent(Request $request){ $validatedData = $request->validate([ 'name' => 'required|max:120', 'email' => 'required|unique:students', 'mobile' => 'required|integer|max:10' ], [ 'name.required' => "Name field is required", 'name.max' => "Maximum length of name field if upto 120 chars" ]); // The student data is valid... // save data }
- We have provided the custom messages for Name validation rules of required and max. Same we can do for all rest inputs.
By Custom Form Request Validation Class
Inside this section of validation, assume we have the same routes created, controller and view file.
To create a request class file, we will use artisan make:request command. Back to terminal
$ php artisan make:request StoreStudentData
This command will generates a class file which is automatically placed into app/Http/Requests directory. If we open, we should see we have authorize(), rules() methods. Inside this method rules() we provide the form validation rules.
/** * 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:120', 'email' => 'required|unique:students', 'mobile' => 'required|integer|max:10' ]; }
- We have defined form validation rules in key and value pairs.
Next, Back to Controller file
# Import Request use App\Http\Requests\StoreStudentData; # Use in Method public function saveStudent(StoreStudentData $request) { // Retrieve the validated input data... $validated = $request->validated(); // The student data is valid... // save data }
- We loaded custom request class called StoreStudentData. And also called validated() method. If validation fails then it automatically redirected to it’s previous route from where it came. Other wise in case of success it will do rest of the operations.
- When we will get errors it will display system handled error messages.
Change Default Error Messages
Simply, we need to define a messages() method into Request class what we have created. Open StoreStudentData.php file and write this method into it.
/** * Get the error messages for the defined validation rules. * * @return array */ public function messages() { return [ 'name.required' => "Name field is required", 'name.max' => "Maximum length of name field if upto 120 chars" ]; }
Creating Manual Validators
Inside this section of validation, assume we have the same routes created, controller and view file as what we did for the first case.
We create a validator instance manually using the Validator facade and do form validations.
Back to controller Student.php
#Import Validator Facade use Illuminate\Support\Facades\Validator; # Method public function saveStudent(Request $request){ $validator = Validator::make($request->all(), [ 'name' => 'required|max:120', 'email' => 'required|unique:students', 'mobile' => 'required|integer|max:10' ]); if ($validator->fails()) { return redirect('add-student') ->withErrors($validator) ->withInput(); } // The student data is valid... // save data }
- The @error directive what we have used to collect error messages at view file, it works perfect for these as well.
- We are using Validator facade to create manual validators.
- $request->all() List all submitted inputs values of form.
- When we have any error, it redirects to redirect(‘add-student’) what we have added in case of fails block.
Using Validator facade with validate()
If we don’t want to use manual redirect after error, we can also use validate() method. It automatically redirects() to it’s previous location.
public function saveStudent(Request $request){ Validator::make($request->all(), [ 'name' => 'required|max:120', 'email' => 'required|unique:students', 'mobile' => 'required|integer|max:10' ])->validate(); // The student data is valid... // save data }
Change Default Error Messages
public function saveStudent(Request $request){ Validator::make($request->all(), [ 'name' => 'required|max:120', 'email' => 'required|unique:students', 'mobile' => 'required|integer|max:10' ], [ 'name.required' => "Name field is required", 'name.max' => "Maximum length of name field if upto 120 chars" ])->validate(); // The student data is valid... // save data }
We hope this article helped you to learn about Laravel 8 Form Validation Methods in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.
Great post. I was checking continuously this blog and I’m impressed!
Extremely useful information specially the last part :
) I care for such info a lot. I was seeking this particular info for a long time.
Thank you and good luck.
Thanks
Hurrah, that’s what I was exploring for, what a material!
existing here at this blog, thanks admin of this web site.
Very good post. I will be going through many of these issues as well..
Thanks for finally writing about > Laravel 8 Form Validation Methods – Online Web Tutor < Loved it!
Thanks for finally talking about >Laravel 8 Form Validation Methods – Online Web Tutor <Liked it!
I blog frequently and I truly appreciate your content.
The article has truly peaked my interest. I will take a note of your website and
keep checking for new details about once a week. I subscribed to your Feed too.
Excellent post. I definitely appreciate this website. Keep writing!
Hi there to all, as I am genuinely keen of reading this weblog’s post to be updated on a regular basis.
It includes nice material.
Hi i am kavin, its my first occasion to commenting
anywhere, when i read this post i thought i could also create comment due to
this brilliant paragraph.
Very quickly this web page will be famous among all blog users, due to it’s fastidious
posts
Thanks very interesting blog!
I think the admin of this website is genuinely working hard in favor
of his site, as here every data is quality based information.
Thanks
I used to be able to find good info from your articles.