Home > database >  How do I define validation rules in laravel 8 globally?
How do I define validation rules in laravel 8 globally?

Time:12-24

I have considered defining validation rules for different parts of my application in a class as static variables. For example,

$VALIDATION_RULES = [
    'signatures' => [
        'first_name' => ['required', 'max:255', 'required','string'],
        'last_name' => ['required', 'max:255', 'required', 'string'],
        'enabled' => [ 'required', Rule::in(['on', 'off']) ],
        'signature_file' => ['required', 'mimes:png,jpeg,jpg', 'max:1024'],
        'operator_id' => ['required', 'numeric'],
    ],
];

However, I get this error.

Symfony\Component\ErrorHandler\Error\FatalError
Constant expression contains invalid operations

This is due to

Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed. In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.

according to the php official documentation. What is the correct way to do this?

P.S.: This variable is defined inside a class as a public and static member. In the code, wherever I need to validate an input, I can call

$validated_input = $request->validate($VALIDATION_RULES['signatures']);

This way, I can have all the rules centralized in one class.

CodePudding user response:

If you want to have a part of a code and use it in the other FormRequests too, you can use traits.

Suppose you want to validate users in the multi FormRequests:

Create UserRequestTrait and add this method to the trait:

private function userInfoValidator(string $prefix = ''): array
{
    return [
        $prefix . 'first_name' => ['required', 'string', 'max:100'],
        $prefix . 'last_name' => ['required', 'string', 'max:100'],
    ];

}

Now you can use it in the FormRequest classes:

class UserFormRequest extends FormRequest
{
    use UserRequestTrait;


    public function rules()
    {

        $rules = [
          // Add the other rules
        ];

        // validate user info
        $userValidation = $this->userInfoValidator();

        return array_merge(
            $rules,
            $userValidation
        );
    }
}

And if you are validating an object, you can add the prefix in the userInfoValidator method, like this:

$userValidation = $this->userInfoValidator('users.*.');

CodePudding user response:

You cannot use functions ,expressions,objects while declaring class properties (includes static and non-static property).which means you cannot call someFunction() or new Sampleclass inside the property, you can only use static values. You'll have to add those values differently inside the constructor or maybe some other method.

so By removing Rule::in(['on', 'off']) inside the property (which is object) will fix the issue

    class MyTestClass {
  
  public $VALIDATION_RULES = [
    'signatures' => [
        'first_name' => ['required', 'max:255', 'required','string'],
        'last_name' => ['required', 'max:255', 'required', 'string'],
        'enabled' => [ 'required'],
        'signature_file' => ['required', 'mimes:png,jpeg,jpg', 'max:1024'],
        'operator_id' => ['required', 'numeric'],
    ],
];
    
}

$obj = new MyTestClass;
dd($obj);

You can read the docs

https://php-legacy-docs.zend.com/manual/php5/en/language.oop5.static

  • Related