Laravel Validation and Rules: Validate Inputs using Laravel Validator Class and display errors

Validate-Inputs-using-Laravel-Validator-Class-and-displa-errors

Of course validation is a very important part of our web application development.When it comes to implement validation from backend,laravel has inbuilt validation class that provides few unique ways to deal with validation in your application’s coming data.

In this tutorial we will see how to use validator class to validate inputs in laravel application.

Validation inside Controller(From Controller’s Approach):

This validation I am going to implement from controller. Please find below the code.

<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Response;
use \Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use Validator;
class AddressController extends Controller
{
public function index(){
return view('create');
}public function insert(Request $request){
$validator = Validator::make($request-&gt;all(), [
'name'=>'required',
'email'=>'required|email',
'mobilenumber'=>'required|regex:/[0-9]{10}/|digits:10'
]);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator->getMessageBag()->toArray());
}else{
// Do your stuff
}
}
In the above validation it states that if the validation fails then the method creates a proper error message and send it back to the view. If the validation passes, it will just execute the code inside the action.
To check laravel validation rules go through Laravel Validation rules list

First Fails and Stop Next:

Laravel has rule to Stop On First Validation Failure.Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, we can set bail rule :with first rule validation.Find below the example.

$validator = Validator::make($request->all(), [
'name'=>'bail | required',
'email'=>'required|email',
'mobilenumber'=>'required|regex:/[0-9]{10}/|digits:10'
]);
​That’s All,thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this tutorial let us know. We’d love to help! Get in touch with us.