Validation in Laravel

Dikshant Rajput
4 min readAug 22, 2021

Validation is one of the most important part of any backend service. Protecting your forms from unwanted responses that can be potentially used to hack your system or create any mishappening. Whenever taking data from users through forms or any other medium, one should be very careful. Each and every response should be checked before going on to the servers or databases.

Laravel provides very efficient, organised and an easy way for validating responses or requests. It can even be used for checking uniqueness, correct form of data and other stuff. It’s very easy in Laravel to validate http request with use of validate method of the Request class.

Laravel includes a wide variety of convenient validation rules that you may apply to inputs. It provides a very simple way to show error messages directly to the blade file.

There are various ways to validate requests in Laravel. Some of most commonly used methods are:

Validate method:

Syntax:

The validate method accepts max of 2 parameters, first one is the array of rules and second one is the array of messages.

validate($rules,$messages);public function store(Request $request){
$request->validate(
[
'email' => ['required','email','unique:users'],
'name' => ['required','max:40']
],[
'name.required' => 'Please enter your name',
'name.max' => 'Name should not exceed 40 characters',
]);
}

The rules can be written like this also:

'email' => 'required|email|unique:users'

As you can see there are multiple rules applied on a single ‘email’ field.

If you want Laravel to stop on the first rule, you can add ‘bail’ to the rules like this:

'email' => 'bail|required|email|unique:users'

If you want to apply validation on nested object like you have an array of input variable and you want to apply validation on elements in the array, you can do like this:

'book.name' => 'required' 

Validator facade

Laravel provides a facade if you don’t want to apply validation using validate method. There are some extra functionality provided by the facade like redirecting the user to some other page if the validation fails.

You can implement validation using facade like this:

Syntax:

Validator facade have a method named ‘make’ that is used to implement validation. It accepts 3 parameters. First one is the fields on which the validation is to be applied, Second one is the rules and third one is the custom messages to show. Each parameter is an array.

Validator::make($fields,$rules,$message)use Illuminate\Support\Facades\Validator;public function store(Request $request){
$validator = Validator::make(
[
'email' => $request->email,
'name'=>$request->name
],
[
'email' => ['required','email','unique:users'],
'name' => ['required','max:40']
],[
'name.required' => 'Please enter your name',
'name.max' => 'Name should not exceed 40 characters',
]);
}

Laravel automatically redirects back to the route from which the request is initiated with the error messages. If you want to redirect to somewhere else, you can use the ‘fails’ method to check if the validation is failed .

if($validator->fails()){
return redirect()->route('abc')
->withInputs($request->all())
->withErrors($validator);
}

If you want to check if validation passes, there is a method for it too:

if($validator->passes()){
//
}

To get validated fields, you can use the validated method or safe method. Additionally, you can even get only the fields you wan to use or can exclude some fields like these:

$validator->validated(); //array of validated fields$validator->safe()->all();$validator->safe()->except(['password']);$validator->safe()->only(['email','name']);

If you want to make the collection of safe fields, you can do it like this:

$validator->safe()->collect(); 

If you want to stop validator to run after the first failure, you can use “stopOnFirstFailure” method chained with “fails” method available with Validator facade like this:

if ($validator->stopOnFirstFailure()->fails()) {
// ...
}

FormRequests

Syntax:

public function store(UserRequest $request){
//
}

An efficient way of creating validation and validating http request inputs is by using FormRequests that can be easily created by composer command:

php artisan make:request UserRequest

The form requests have rules method for making rules and messages method for making custom messages like this:

//for stoping on first failureprotected $stopOnFirstFailure = true;public function rules()
{
return [
'email' => 'required|email|unique:users',
'name' => 'required',
];
}
public function messages()
{
return [
'email.required' => 'Please enter email',
'name.required' => 'Please enter name',
];
}

All the available validation methods are listed here:

I hope you like the blog and if you do, then don’t forget to hit that clap icon and if you want to read more such blogs, do follow me.

--

--