1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @package Sofa\Eloquence |
5
|
|
|
* @author Jarek Tkaczyk <[email protected]> |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
use Illuminate\Database\Eloquent\Model; |
9
|
|
|
|
10
|
|
|
if (!function_exists('rules_for_update')) { |
11
|
|
|
/** |
12
|
|
|
* Adjust unique rules for update so it doesn't treat updated model's row as duplicate. |
13
|
|
|
* |
14
|
|
|
* @link http://laravel.com/docs/5.0/validation#rule-unique |
15
|
|
|
* |
16
|
|
|
* @param array $rules |
17
|
|
|
* @param \Illuminate\Database\Eloquent\Model|integer|string $id |
18
|
|
|
* @param string $primaryKey |
19
|
|
|
* @return array |
20
|
|
|
*/ |
21
|
|
|
function rules_for_update(array $rules, $id, $primaryKey = 'id') |
22
|
|
|
{ |
23
|
|
|
if ($id instanceof Model) { |
24
|
|
|
list($primaryKey, $id) = [$id->getKeyName(), $id->getKey()]; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
// We want to update each unique rule so it ignores this model's row |
28
|
|
|
// during unique check in order to avoid faulty non-unique errors |
29
|
|
|
// in accordance to the linked Laravel Validator documentation. |
30
|
|
|
array_walk($rules, function (&$fieldRules, $field) use ($id, $primaryKey) { |
31
|
|
|
if (is_string($fieldRules)) { |
32
|
|
|
$fieldRules = explode('|', $fieldRules); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
array_walk($fieldRules, function (&$rule) use ($field, $id, $primaryKey) { |
36
|
|
|
if (strpos($rule, 'unique') === false) { |
37
|
|
|
return; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
list(,$argsString) = explode(':', $rule); |
41
|
|
|
|
42
|
|
|
$args = explode(',', $argsString); |
43
|
|
|
|
44
|
|
|
$args[1] = isset($args[1]) ? $args[1] : $field; |
45
|
|
|
$args[2] = $id; |
46
|
|
|
$args[3] = $primaryKey; |
47
|
|
|
|
48
|
|
|
$rule = 'unique:'.implode(',', $args); |
49
|
|
|
}); |
50
|
|
|
}); |
51
|
|
|
|
52
|
|
|
return $rules; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|