Skip to content

Instantly share code, notes, and snippets.

@lotsofbytes
Last active October 6, 2018 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lotsofbytes/5a28d080d8dc4a45578895ddf068c031 to your computer and use it in GitHub Desktop.
Save lotsofbytes/5a28d080d8dc4a45578895ddf068c031 to your computer and use it in GitHub Desktop.
[バリデーション:unique] #laravel #L55 #validation

バリデーション:unique

入力値が、指定のDBテーブルのコラムにおいて重複がないことを判定。DBレコードの追加時に使用。編集時には、現在のレコードを外して判定するために、 ignoreの引数の指定が必要。あるいは、Ruleを使用してignoreで指定。

laravel 5.5

gistの画面

以下の実行で、ダウンロードできます

$ 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],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment