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