The Standard Approach to Validate Laravel Form Request
Laravel is one of the best choices for PHP developer since it gives so much flexibility to the developer. However, the form validation is one of the crucial parts for web-based application and API. Laravel makes Validating the request is so simple. We just set the rules and call the validator to check whether the request meets the rules or not. Return the error message to the session if it doesn’t meet the rules to print in view, otherwise, pass to the next level to execute. A sample code is-
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
This code will return the error message once executed.
Easy enough, right?
Now, still, if you have a question in your mind that, is it the best approach to handle laravel form request, I would love to say no. We can make it better.
Let’s see how-
Since you are here, it seems that you love to write simple code. We will apply “form request” validation to keep our controller slim. Form requests are basically custom request classes that contain validation logic.
Let’s create a custom form request class by the following command.
php artisan make:request StoreBlogPost
This will generate a class that will be placed in the app/Http/Requests
directory.
The file will be looks like-
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreBlogPost 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 [
//
];
}
}
Laravel Form Request class has two default methods auth() and rules(). You can perform any authorization logic in auth() method based on your business logic.
Now, you need to define rules in the rules() method.
public function rules()
{
return [
'title' => 'required',
'body' => 'required'
];
}
Now, let’s define a custom message for each rule. To do so, you need to define a method name messages() in this class.
/**
* Custom message for validation
*
* @return array
*/
public function messages()
{
return [
'title.required' => 'Hay, you have to put the title that is required!',
'body.required' => 'The body is required too, man!',
];
}
Once done, you just import this class in your controller, and inject this class as follows-
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreBlogPost;
class BlogPostController extends Controller
{
public function store(StoreBlogPost $request)
{
// it will return only the validated data
$validated = $request->validated();
}
}
The main purpose to have this in our controller is to make slim and easy to maintain our controller. Now our controller doesn’t need to worry about any validation logic. We have our own validation class with only one response to handle validation and let controller do there work.
Now again, if validation fails, it will redirect the user to the previous page with an error that will be flash in sessions. If the request was an AJAX then a response with 422 status code will be return with an error in JSON format.
If you have any query, suggestion, and opinion, let’s discuss here. Thank you.