2

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...

2
  • laravel.com/docs/9.x/validation#custom-validation-rules Commented Jun 1, 2022 at 13:12
  • 1
    I will create a custom validation rule for it anyway, the question what column it will be linked to or where to place this custom validation Commented Jun 1, 2022 at 13:19

2 Answers 2

2

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!');
            }
        });
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think this is what I was looking for, I can specify an error key that is not related to field key
This would require to implement the same logic overriding the method after in all similar requests, and in turn, possibly result in another class to be extended.
-2

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],

2 Comments

this answer is not relevant, please take a look at current answer to understand what was the question
Just in case, ihe question states: ...not related to either name or permission column.... The "column" likely means attribute a ValidationRule refers to. This answer does not cover the required absence of the attribute at this point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.