Nikita Kolotilo
Nikita Kolotilo

Reputation: 85

How to validate pair uniqueness in array in Laravel?

I'm developing CRUD for Laravel application for Tariff entity. Tariff table has such structure for now:

--------------------------
|id | name | hint | price|
--------------------------

I also have many-to-many relation with services included in tariffs. The binding table structure is:

----------------------------------------------
| id | tariff_id | service_id | type | value |
----------------------------------------------

On database level pair of tariff_id & service_id are unique (Specific tariff cannot have 2 same services: (1-1) & (1-1)).

I made vue table component for adding services to tarrifs and trying to validate this case using laravel validation rules.

Here is a piece of FormRequest data I get from table component

"id" => 3,
"services" => array:2 [▼
    0 => array:3 [▼
      "service_id" => "2"
      "duration_type" => "0"
      "duration_value" => "1"
    ]
    1 => array:3 [▼
      "service_id" => "3"
      "duration_type" => "0"
      "duration_value" => "2"
    ]
]

My validation rules for services are:

'services' => 'required|array',
    'services.*.service_id' => [
    'required',
    'string'
    ],
    'services.*.duration_type' => 'integer|min:0|max:1',
    'services.*.duration_value' => 'required|string',

The question is: How do I check uniqueness for current service_id & tariff_id? I mean when I write something like 'services.*.service_id' it's iterating somehow through my array of data so I need to compare current iteration's service_id to tariff_id.

Would be glad if someone can help me with this situation, mayber there's another way to make it work. To prevent user insert non-unique data I put try catch block in my controller & when MySQL error happens controller just fires alert. It's working but feels cumbersome.

Upvotes: 0

Views: 204

Answers (1)

Steve
Steve

Reputation: 50

Did you try using the validation rule unique? Something like

'services.*.service_id' => [ 'required', 'string', 'unique:tariff_services,service_id' ]

where tariff_services is the name of the pivot table?

Upvotes: 1

Related Questions