Created
July 5, 2019 02:35
-
-
Save youhey/1b4c011c099d39ed5241268162df2809 to your computer and use it in GitHub Desktop.
Laravel の独自バリデーションを頑張って考えてたら、それは `distinct` という標準ルールだったでゴザル……。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Contracts\Validation\Rule; | |
use Illuminate\Http\Request; | |
// 'items.*.id' => [ | |
// 'required', | |
// 'integer', | |
// 'min:1', | |
// 'max:999', | |
// new Distinct('items.*.id', $this) | |
// ] | |
// | |
// それって…… | |
// | |
// 'required|integer|min:1|max:999|distinct' | |
// じゃね? | |
class Distinct implements Rule | |
{ | |
private $attribute; | |
private $request; | |
public function __construct(string $attribute, Request $request) | |
{ | |
$this->attribute = $attribute; | |
$this->request = $request; | |
} | |
public function passes($attribute, $value) | |
{ | |
$ids = data_get($this->request->all(), $this->attribute); | |
$stat = array_count_values($ids); | |
return (@$stat[$value] ?? 0 === 1); | |
} | |
public function message() | |
{ | |
return 'The :attribute duplicate'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment