Komal
Komal

Reputation: 2736

Validation for combination of two fields in laravel 5

Can we validate combination of two fields I don't want same entry in my events table For example

no | event     | category
----------------------
1  | Wedding   | Band
2  | Wedding   | Food
3  | Wedding   | Decor
4  | Wedding   | Band  // laravel validation to avoid this

Like unique event

'event' => 'required|unique:events'

Anything like this

'event' => 'required|unique:events|category:unique'

Upvotes: 2

Views: 4751

Answers (2)

Itay Hamashmid
Itay Hamashmid

Reputation: 151

This is an old question but I ran into the same problem so here's my quick fix. On App\Providers\AppServiceProvider, inside the boot() method, add this:

Validator::extend('uniqueCombo', function ($attribute, $value, $parameters, $validator) {

$query = DB::table($parameters[0])
    ->where($attribute, '=', $value)
    ->where($parameters[1], '=', request($parameters[1]));

if (isset($parameters[2])) {
    $query = $query->where('id', '<>', $parameters[2]);
}

return ($query->count() <= 0);

});

Use it like this for create:

'column' => 'uniqueCombo:table,other_column'

And like this for update:

'column' => 'uniqueCombo:table,other_column,instance_id'

Just make sure that on the request you'll have an input with name="other_column".

Hope that helps someone. :)

Upvotes: 1

Shaunak Shukla
Shaunak Shukla

Reputation: 2347

Below rule checks for Unique event name under given $categoryName. $categoryName can be Band, Food, Decore, any!

For example, if Event is 'Wedding' and category is 'Band', It will not let you insert, it will throw error of already exist. If Event is 'wedding' and category is 'Any', it will let you insert.

'event' => 'required|unique:events,event,NULL,id,category,'.$categoryName

You can find documentation of it here, you have to search for keyword 'Adding Additional Where Clauses' on that page.

Upvotes: 3

Related Questions