0

I'm using Laravel 5.1 , I've a model Customer which has many Vehicles. I set validations for Vehicle model like this :

public static $Rules = array(
    'code' => 'required|unique:vehicles', 
    'registernumber' => 'required|unique:vehicles'                       
);

Till now, all is fine : I can't insert two vehicles with the same code or registernumber.
What I want to do is :
Can I set a custom validation which allows me to insert unique code or registernumber value just for a given CustumerID ?

Example :

Customer1 :
Vehicle1: code1, registernumber1
Vehicle2: code2, registernumber2

  (Here I can't insert for example two codes having 'code1' value with Customer1)

Customer2 :
Vehicle1: code1, registernumber1
Vehicle2: code5, registernumber5

  (Here I can't insert for example two registernumbers having 'registernumber5' value with Customer2)

Any idea please ?

BKF
  • 1,298
  • 4
  • 16
  • 35
  • Instead of going in model ..can you do it in backend at database level...check this [link](http://stackoverflow.com/a/15800279/3202287) adding unique constraint for multiple columns – narasimharaosp Jan 21 '16 at 18:17
  • That's in SqlServer ! what about MySql ^^' – BKF Jan 21 '16 at 18:29

2 Answers2

0

Syntax

 ALTER TABLE `tablename`
 ADD UNIQUE KEY `my_unique_key` (`colname1`, `colname2`);

In your example

 ALTER TABLE `yourtable`
 ADD UNIQUE KEY `unique_reg` (`customername`, `vehicle`, `code`, `regno`);

Try this but you should handle the db_error otherwise it affects the user experience

narasimharaosp
  • 533
  • 3
  • 12
0

As long as the customer id is in that table. The way the unique validation rule works is as follows:

unique:
    [table name, optionally with a connection name],
    [the column you are checking for uniqueness, optional],
    [the id of the row that will be ignored in the check (for example if you are updating a row, you want the row you are updating to not be included), optional],
    [the column name that contains the id you are running the check against, optional],
    [additional where clauses (where_column, where_value)]

So, if your table schema looks like this:

vehicle_id, code_number, registration_number, customer_id

And you only want to run the unique check for rows of the same customer, you can do this:

$customer_id = 'whatever';

$Rules = array(
    'code' => 'required|unique:vehicles,code_number,NULL,vehicle_id,customer_id,'.$customer_id                     
); 

That will run the check only on rows where('customer_id', $customer_id)

Patrick Stephan
  • 1,809
  • 16
  • 23