Where should the data be validated, in the model or in the controller?

0

Initially we know that the validations from javascript must be obligatory, my doubt is in the driver or model.

Normally I perform validations of laravel validation in the controller, taking into account that these validations perform the assignment of null in case the data is not sent by the user, limits, regex, etc, with this it is assumed that when it arrives to the model the data is validated.

If an API is being used, the API driver must perform the same validations. This allows code duplication. If everything is validated in the model, then before the process arrives until the validations of the model, it must go through the entire process of the controller, something that does not seem very good since there is a greater consumption of resources and execution.

What do you consider to be the correct path? Validate in the controller or model, or both ?, taking into account performance and good coding practices.

My question is, where should the validations be done, in the controller or in the model?

    
asked by millan2993 21.02.2018 в 22:24
source

1 answer

1

As I understood, I think the Form Request Validation section of the documentation can help you.

By php artisan make:request UnStoreRequest you generate a class so that you can do all your validations there.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UnStoreRequest 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 [
            //
        ];
    }
}

The previous thing you can REUSE it in the functions that you want, for example in your API.

use App\Http\Requests\UnStoreRequest;

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

So, if you are going to validate something, first go through that class, your validations would be written in that class.

    
answered by 21.02.2018 в 23:53