Search code examples
phplaravelvalidationlaravel-livewire

Laravel Livewire - Constant expression contains invalid operations in $rules property


I tried to define some validation rules in my livewire component to validate some FormData:

protected $rules = [
    'website' => 'url|nullable',
    'zipcode' => 'regex:/\b\d{5}\b/|nullable',
    'founding_year' => 'required|digits:4|integer|min:1700|max:2020',
];

That work's very well until I need to validate against the value of a variable or a dynamic value in general.

E.g.: Changing the max property from hardcoded 2020 to the current year:

 protected $rules = [
   ...
   'founding_year' => 'required|digits:4|integer|min:1700|max:'. date('Y'),
];

Unfortunatelly this resolves in an exception:

Symfony\Component\ErrorHandler\Error\FatalError

Constant expression contains invalid operations

Has someone an idea how to fix this?


Solution

  • You can't call functions or methods when declaring the value of a property directly in PHP.

    With Livewire, you can specify a rules() method which returns the rule-array instead - this allows you to use functions in the rules. Internally, Livewire will now run the result of that method instead of grabbing the protected $rules array. This means you can still hook into the $this->validate() and $this->validateOnly() methods Livewire ships with.

    So instead of defining your protected $rules; attribute, declare the rules() method,

    public function rules() 
    {
        return [
            'website' => 'url|nullable',
            'zipcode' => 'regex:/\b\d{5}\b/|nullable',
            'founding_year' => 'required|digits:4|integer|min:1700|max:'.date("Y"),
        ];
    }