Search code examples
phpvalidationlaraveluniquelaravel-5.1

Waht's the best way to use unique validation according to an attribute in a table


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 ?


Solution

  • 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)