How to validate Request data in Laravel?

Laravel-validation-errors

Laravel provides several different approaches to validate your application’s incoming data. It is most common to use the validate method available on all incoming HTTP requests. There are multiple ways to vaidate the incoming Request data in Laravel. The beast part is, if validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated and if the incoming request is an XHR( Ajax ) request, a JSON response containing the validation error messages will be returned. Laravel Validation rules are very well documented here. If the validation fails, the response will automatically be generated and if the validation passes, our request will be executing normally. To better understand the validate method, let’s check this working of the validation here:

1. Default Validator

$request->validate([
    'title'=>'required|max:255',
    'description'=>'required'
]);

As you can see, the validation rules are passed into the validate method.
Also, validation rules may specified as arrays of rules instead of a single | delimited string as like below:

$request->validate([
    'title' => ['required','max:255'],
    'description' => ['required'],
]);

If the incoming HTTP request contains “nested” field data, you may specify these fields in your validation rules using “dot” syntax:

$request->validate([
    'title' => 'required|max:255',
    'user.name' => 'required',
    'user.bio' => 'required',
]);

2. Manually Creating Validators

The Validator class provides an awesome array of validation helpers to make validating your data. Let’s walk through an example:

Get an array of data you want to validate:

$input = Input::all();

Define the validation rules for your data:

$rules = array(
    'title'  => 'required|max:255',
    'description' => 'required',
);

Create a Validator instance and validate the data:

$validator = Validator::make($input, $rules);
 
if ($validator->fails())
{
    return redirect()->back()
        ->withErrors($validator)
        ->withInput();
}

 

To display the validation error messages, please check this tutorial here: How to Retrieve validation Error Messages in Laravel View/Blade file?

Please follow and like us:

Related Posts

Leave a Reply

Share