Home > database >  Where to put Laravel validation that is not related to column
Where to put Laravel validation that is not related to column

Time:06-02

For example, I have an HTTP request that handles some entity creation (let it be Role) And validation looks like this:

class CreateRole extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'permissions' => ['required', 'array'],
...

And I have some restrictions that are not related to either name or permission column. For example the maximum amount of roles that can be created.

Such custom validation can be placed to the name property, but it looks wrong.

PS: I know about custom validators. Question about where to place it...

CodePudding user response:

You can use after hook in the form request CreateRole.php

class CreateRole 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<string, mixed>
     */
    public function rules()
    {
        return [
            'title'  => ['required', 'string', 'max:255'],
            'permissions' => ['required', 'array'],
        ];
    }
    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if (Role::count() > 10) {
                $validator->errors()->add('limit', 'Max number of Roles reached!');
            }
        });
    }
}

CodePudding user response:

You have to create custom validation class as shown in this Laravel document and place into you validatior class like below.

 'name' => ['required', 'string', new CustomValidationClass],
  • Related