入力値が、指定のDBテーブルのコラムにおいて重複がないことを判定。DBレコードの追加時に使用。編集時には、現在のレコードを外して判定するために、 ignoreの引数の指定が必要。あるいは、Ruleを使用してignoreで指定。
以下の実行で、ダウンロードできます
$ git clone git@gist.github.com:5a28d080d8dc4a45578895ddf068c031.git tests/Unit/Validations/Unique
入力値が、指定のDBテーブルのコラムにおいて重複がないことを判定。DBレコードの追加時に使用。編集時には、現在のレコードを外して判定するために、 ignoreの引数の指定が必要。あるいは、Ruleを使用してignoreで指定。
以下の実行で、ダウンロードできます
$ git clone git@gist.github.com:5a28d080d8dc4a45578895ddf068c031.git tests/Unit/Validations/Unique
<?php | |
namespace Tests\Unit\Validations\Unique; | |
use Tests\TestCase; | |
use Illuminate\Foundation\Testing\RefreshDatabase; | |
use Illuminate\Validation\Rule; | |
use Validator; | |
use App\User; | |
class UniqueTest extends TestCase | |
{ | |
use RefreshDatabase; | |
/** | |
* @test | |
* @dataProvider provider_unique | |
*/ | |
public function unique($input, $expected) | |
{ | |
// \DB::enableQueryLog(); | |
// DBに1つだけレコードを作成 | |
$user = factory(User::class)->create([ | |
'email' => 'test@example.com' | |
]); | |
$v = Validator::make( | |
$input, | |
['email' => 'required|unique:users,email'] | |
); | |
$this->assertEquals($expected, $v->passes()); | |
// print_r(\DB::getQueryLog()); | |
} | |
public function provider_unique() | |
{ | |
return [ | |
[['email' => 'test@example.com'], false], | |
[['email' => 'test2@example.com'], true], | |
]; | |
} | |
/** | |
* @test | |
* @dataProvider provider_uniqueIgnore | |
*/ | |
public function uniqueIgnore($input, $expected) | |
{ | |
// \DB::enableQueryLog(); | |
// DBに1つだけレコードを作成 | |
$user = factory(User::class)->create([ | |
'email' => 'test@example.com' | |
]); | |
$v = Validator::make( | |
$input, | |
['email' => 'required|unique:users,email,' . $user->email . ',email'] | |
); | |
$this->assertEquals($expected, $v->passes()); | |
// print_r(\DB::getQueryLog()); | |
} | |
/** | |
* @test | |
* @dataProvider provider_uniqueIgnore | |
*/ | |
public function uniqueRuleIgnore($input, $expected) | |
{ | |
// \DB::enableQueryLog(); | |
// DBに1つだけレコードを作成 | |
$user = factory(User::class)->create([ | |
'email' => 'test@example.com' | |
]); | |
$v = Validator::make( | |
$input, | |
[ | |
'email' => [ | |
'required', | |
Rule::unique('users')->ignore($user->email, 'email') | |
] | |
] | |
); | |
$this->assertEquals($expected, $v->passes()); | |
// print_r(\DB::getQueryLog()); | |
} | |
public function provider_uniqueIgnore() | |
{ | |
return [ | |
[['email' => 'test@example.com'], true], | |
[['email' => 'test2@example.com'], true], | |
]; | |
} | |
} |