我可以使用laravel验证器来确保输入数组中的项是唯一的吗?

时间:2017-05-01 00:01:29

标签: php laravel validation

给定四个表单字段,命名为数组:

<input type="text" name="items[]">
<input type="text" name="items[]">
<input type="text" name="items[]">
<input type="text" name="items[]">

是否可以使用laravel验证类来确保每个项目值都是唯一的?

我试过了:

$this->validate($request, [
    'items' => 'array|size:4|required',
    'items.*' => 'distinct'
]);

items.*部分似乎没有任何效果。我错过了什么?

编辑:这是我使用的phpunit测试:

$this->signIn();

$topic = create('App\tfTopic');

$this->post($topic->path().'/lists', ['items' => [
    "One is the loneliest number", 
    "One is the loneliest number",
    "Two is great", 
    "Three can be as bad as one" 
    ]])
    ->assertSessionHasErrors('items');

如果我添加到我的控制器:

dd(gettype(request('items')));

它以&#34;数组而死。&#34;

当我运行测试时,它失败了:

Session missing error: items
Failed asserting that false is true.

1 个答案:

答案 0 :(得分:1)

只需将您的后期测试更改为:

$this->post($topic->path().'/lists', ['items' => [
    "One is the loneliest number", 
    "One is the loneliest number",
    "Two is great", 
    "Three can be as bad as one" 
    ]])
    ->assertSessionHasErrors(['items.0', 'items.1']);