Laravel – Using FormRequest for validation

0
60

Data validation is very important to ensure input from the user to match the needs that we need, for example if we need to save email from the user, then the user is only allowed to input data in the email format. In addition, data validation is also needed to avoid damaging applications by injection methods, such as XSS Injection for example.

Laravel has made it easy for us to validate user input. Generally there are 3 ways to validate user input using Laravel. In this tutorial we will not discuss in detail all three, we will only discuss about how to write and why you should consider using FormRequest for validation so that the code we write is cleaner.

Now let's look at how to write the validation of each.

Facade Validator

Below is an example of writing validation using the Validator facade.

RoleController class extends Controller
{
    public function store (Request $ request)
    {
        $ validator = Validator :: make ($ request-> all (), [
            'name'  => 'required|max:30',
        ]);
        
        if ($ validator-> fails ()) {
            redirect () -> back ()
                -> withErrors ($ validator-> errors ());
        }
    }
}

Helper Controller

The controller itself has a helper method by name validate () to validate requests from users declared in the trait Illuminate Foundation Validation ValidatesRequests. If we look, the base controller that we used when we first installed Laravel uses this trait.

App  Http  Controllers namespace;

Controller class extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

The following is an example of using a method validate on the controller to validate input from the user.

RoleController class extends Controller
{
    public function store (Request $ request)
    {
        $ this-> validate ($ request, [
            'name'  => 'required|max:30',
        ]);

        //
    }
}

There is nothing wrong with using the two methods above to validate user input. This is just a matter of standardization and selection of the way of the developer itself. I personally prefer to use the third method, which is to use FormRequest.

By using FormRequest all validation rules are described in separate classes, in other words outside the controller class itself. By separating out all the validation rules on the request form, of course, the lines of code we write on the controller become even smaller. For those of you who embrace the concept of "thin controller"Of course you will consider using FormRequest for validation of user input.

FormRequest

Validation using FormRequest do require a few more steps and seem complicated at the beginning. However, in my opinion there are some advantages that we can get, for example the controller becomes leaner and easier to read, because validation is stored in one place so that the maintenance and debugging process will be easier.

The first step to validate using data FormRequest, we must create a class FormRequest by using the artisan command, for example:

php artisan make: RoleRequest request

The above command will generate a new file in the directory app / Http / Requests with the file name RoleRequest.php. By default, there are 2 methods in the class generated by the artisan command above, i.e.authorize () and rules ().

Authorize method

Method authorize is used to ensure that users are allowed to make requests. The value of the method authorize it must return a value true so the user can proceed to the validation process. This method can be used for various purposes, for example only users who are logged in can make requests and continue the validation process.

/ **
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 * /
public function authorize ()
{
    return Auth :: check ();
}

Method rules

This method is what we use to define all validation rules that we will use to validate a request from the user.

/ **
 * Get the validation rules that apply to the request.
 *
 * @return array
 * /
public function rules ()
{
    return [
        'name'  => 'required|max:30',
    ];
}

The complete code from the FormRequest example above will look something like this. We just need to adjust the validation rules that will be used in the method rules.

the RoleRequest extends FormRequest class
{
    / **
     * 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 [
            'name'  => 'required|max:30',
        ];
    }
}

There are still many methods that we can use in the FormRequest class, such as custom error messages, custom attributes and others. We will discuss in more detail the use of FormRequest in other tutorials.

Those are the three common ways used to validate user input using Laravel. Which do you choose? Please determine according to your own choice and comfort.

The post Laravel – Using FormRequest to appear first on Lab-Informatics validation.

LEAVE A REPLY

Please enter your comment!
Please enter your name here