Caius Caius - 3 months ago 14
PHP Question

Is there a way to check if a couple of inputs are unique in laravel 5.2?

update



What I have is a table with these columns:

- ID
- production_year
- type


If the
type
is already present in the table with the value the user wants to pass, check if
production_year
is already present too, but fail the validation ONLY if these values are present in the same record. Otherwise let the user to store this record.

I'm trying to check the uniqueness of a couple of fields in the same record...

I've seen the documentation about the conditional validation, but I didn't quite find the answer there.

the code



public function rules()
{
return [
// I'd like to check the uniqueness of both of them. In the same record
'production_y' => 'required|unique',
'fk_type' => 'required|unique',
];
}


Any idea? Thanks!

Answer

Can't test right now, can you try:

public function rules()
{
    $type = $this->get('fk_type');

    return [
        'production_y' => "required|unique:your_table,production_year,NULL,id,type,{$type}",
        // ...
    ];
}

Explaination:

  1. unique:your_table Set the table for the unique check.
  2. ,production_year This matches with production_y.
  3. ,NULL,id check all the records.

    3.1. if you use like {$id},id it will check uniqueness except the record with the {$id},

  4. ,type,{$type} and the type should be {$type}

That will produce sth. like (not exact query, just to express the idea):

select count(*) from your_table where production_year = $product_y and where type = $type and where id <> null