-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
ModelsExist.php
54 lines (38 loc) · 1.26 KB
/
ModelsExist.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
namespace Spatie\ValidationRules\Rules;
use Illuminate\Contracts\Validation\Rule;
class ModelsExist implements Rule
{
/** @var string */
protected $modelClassName;
/** @var string */
protected $modelAttribute;
/** @var string */
protected $attribute;
/** @var array */
protected $modelIds;
public function __construct(string $modelClassName, string $attribute = 'id')
{
$this->modelClassName = $modelClassName;
$this->modelAttribute = $attribute;
}
public function passes($attribute, $value): bool
{
$this->attribute = $attribute;
$value = array_filter($value);
$this->modelIds = array_unique($value);
$modelCount = $this->modelClassName::whereIn($this->modelAttribute, $this->modelIds)->count();
return count($this->modelIds) === $modelCount;
}
public function message(): string
{
$modelIds = implode(', ', $this->modelIds);
$classBasename = class_basename($this->modelClassName);
return __('validationRules::messages.model_ids', [
'attribute' => $this->attribute,
'model' => $classBasename,
'modelAttribute' => $this->modelAttribute,
'modelIds' => $modelIds,
]);
}
}