1 | <?php |
||
11 | trait Validatable |
||
12 | { |
||
13 | /** |
||
14 | * Boot the trait. |
||
15 | */ |
||
16 | 15 | protected static function bootValidatable() |
|
17 | { |
||
18 | // Hook to execute before creating |
||
19 | static::creating(function (Model $model) { |
||
20 | 15 | $model->validate(); |
|
21 | 15 | }); |
|
22 | |||
23 | // Hook to execute before updating |
||
24 | static::updating(function (Model $model) { |
||
25 | $model->validate(); |
||
26 | 15 | }); |
|
27 | 15 | } |
|
28 | |||
29 | /** |
||
30 | * Validates current attributes against rules |
||
31 | * |
||
32 | * @return bool |
||
33 | * @throws \DomainException |
||
34 | */ |
||
35 | 15 | public function validate() |
|
36 | { |
||
37 | 15 | $validator = $this->getValidator(); |
|
38 | |||
39 | 15 | if ($validator->fails()) { |
|
40 | 2 | throw new \InvalidArgumentException($validator->errors()->first()); |
|
41 | } |
||
42 | |||
43 | 14 | return true; |
|
44 | } |
||
45 | |||
46 | /** |
||
47 | * Get instance of validator |
||
48 | * |
||
49 | * @return \Illuminate\Validation\Validator |
||
50 | */ |
||
51 | 15 | public function getValidator(): \Illuminate\Validation\Validator |
|
52 | { |
||
53 | 15 | return Validator::make($this->attributes, $this->getRules()); |
|
|
|||
54 | } |
||
55 | |||
56 | /** |
||
57 | * Required method that provide collection or rules |
||
58 | * |
||
59 | * @return array |
||
60 | */ |
||
61 | abstract protected function getRules(): array; |
||
62 | } |
||
63 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: