Caius Caius - 4 months ago 71
SQL Question

Laravel 5.2 Validation unique with where clause doesn't work as expected

I'm working on a ERP using laravel 5.2
I need to do this:

When the user tries to create a new bank, the program will perform a validation to check that the given business name and the given ABI code are unique. When the validation will be executed, the program will ignore all those records with value of 1 on deleted column, for both business name and ABI.

The problem is that it's completely ignoring my where clause.
This is the validation rule:

$this->validate($request, [
'business_name' => 'required|max:255|unique:banks,deleted,0',
'abi' => 'required|max:5|min:5|unique:banks,deleted,0'

The columns in the banks table are:

  • id

  • business_name

  • abi

  • disabled

  • deleted

  • // laravel timestamps

If i didn't misunderstood the documentation for Laravel 5.2 this is the correct way to set a where clause in a unique filter...?

Every kind of help will be appreciated!


What you pass as a third parameter is the primary key's value, hence as you don't pass a fourth parameter which identifies the key, it searches for a record with id, by default, that has a value of 0.

So, you need to pass a fourth parameter, this way, it will ignore all the rows with deleted properties that have the value of 1.

$this->validate($request, [
    'business_name'   => 'required|max:255|unique:banks,business_name,1,deleted',
    'abi'             => 'required|max:5|min:5|unique:banks,abi,1,deleted'