Skip to content

Instantly share code, notes, and snippets.

@youhey
Created July 5, 2019 02:35
Show Gist options
  • Save youhey/1b4c011c099d39ed5241268162df2809 to your computer and use it in GitHub Desktop.
Save youhey/1b4c011c099d39ed5241268162df2809 to your computer and use it in GitHub Desktop.
Laravel の独自バリデーションを頑張って考えてたら、それは `distinct` という標準ルールだったでゴザル……。
<?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