Seamus James
Seamus James

Reputation: 991

Can I use the laravel validator to ensure that items in an input array are unique?

Given four form fields, named as an array:

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

Is it possible to use the laravel validation class to ensure that each item value is unique?

I've tried:

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

But the items.* portion doesn't seem to have any effect. What am I missing?

Edit: Here's the phpunit test I'm using:

$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');

If I add to my controller:

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

It dies with "array."

When I run the test, it fails with:

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

Upvotes: 1

Views: 209

Answers (1)

crabbly
crabbly

Reputation: 5186

Just change your post test to this:

$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']);

Upvotes: 1

Related Questions