Reputation: 93
I'm trying to validate some data with laravel, which I have implemented in the Model itself, as such:
class Collection extends Model { protected $guarded = [ 'id' ];
public $allowedDataTypes = [
'Date',
'Text',
'Number',
'Email',
'Checkbox',
'Image',
'File',
];
25 public static $rules = array([
26
27 'fields.*.fieldName' =>
28 [
29 'unique' => 'Please ensure that the fields are uniquely named.',
30 'required' => 'You must specify a name for your fields.'
31 ],
32
33 'fields.*.dataType' =>
34 [
35 'required', 'You must specify a data type for your fields.',
36 'in:'.implode(',', $allowedDataTypes)
37 ]
38
39 ]);
However, upon submitting data, and supposedly having it go through this validation, it gives me the error seen in the title:
Constant expression contains invalid operations in {link to model}:39
I've numbered the lines of code too and I'm not sure why this specifically is happening.
Thanks in advance for any guidance.
Upvotes: 1
Views: 4214
Reputation: 171
It is not possible to use the implode function inside the class variable declaration. This is because the class variables are initiated before runtime.
If you want to use the implode function you can use a function or use the constructor.
For example:
public function rules()
{
return [
'fields.*.fieldName' => [
'unique' => 'Please ensure that the fields are uniquely named.',
'required' => 'You must specify a name for your fields.'
],
'fields.*.dataType' => [
'required', 'You must specify a data type for your fields.',
'in:'.implode(',', $this->allowedDataTypes)
]
];
}
Upvotes: 2