Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel rule validation unique for id

I have a locations table which has a client_id foreign key which links to my Client table. I want to add form validation so that when a new location is created is it unique but only for a given client_id. So client one cant have two locations called America but Client one and two can both have America.

How do you do this with the laravel validation rules

like image 805
user3074140 Avatar asked Dec 11 '17 10:12

user3074140


People also ask

What is unique in laravel validation?

Sometimes you want to ensure that a field is unique in the database so that someone can't add the same item twice, such as the title for a post.

How to use unique validation in Laravel?

So you can use simple unique validation in laravel. The following unique validation rule is simple. And you can use it as follow: The following unique validation rules with column name on controller methods, you can use as follow: Before using unique validation with the rule, you need to import use Illuminate\Validation\Rule;.

How to use the unique rule in formrequest in Laravel 5?

When using the new Laravel 5 FormRequest to update a resource you might run into a little bit of trouble when you want to use the unique rule. You need to pass in the ID of the row for the unique validator to ignore, but how do you get it. Furthermore, if you're using model validation how might you go about it.

How to ignore a table in a unique check in Laravel?

Check the laravel validation documentation. You can specify the table, column and id to ignore. In the rule above, only rows with an account_id of 1 would be included in the unique check. Show activity on this post.

What is the current_password rule in Laravel 9?

The field under validation must be numeric. The field under validation must match the authenticated user's password. This rule was renamed to current_password with the intention of removing it in Laravel 9. Please use the Current Password rule instead.


Video Answer


2 Answers

Check the laravel validation documentation. You can specify the table, column and id to ignore.

'email' => 'unique:users,email_address,'.$user->id

You can also add additional where clauses:

'email' => 'unique:users,email_address,NULL,id,account_id,1'

In the rule above, only rows with an account_id of 1 would be included in the unique check.

like image 94
meewog Avatar answered Oct 01 '22 10:10

meewog


You can use laravel's built in unique validation as,

'client_id' => 'unique:Client table'

and at the time of edit you can pass exception for current row, like

'client_id' => 'unique:Client table,client_id,'.$id

I hope it helps, Thank you...

like image 39
Ritesh Khatri Avatar answered Oct 01 '22 09:10

Ritesh Khatri