Monday, 20 February 2017

Forcing Unique Rule to ignore a given value with additional conditions in Laravel

While checking for unique, sometimes we want to ignore a value. For example Email is unique in User Table. In Profile section if User saves the information without changing the Email then Validator returns an Error as it finds current email already exist. For this we need to tell the Validator to ignore a given value.

'email' => 'unique:user,email,'. $user_id

Here user = table, email = field, $user_id = Given value

If Soft-Delete is ON then we may need another condition

'email' => 'unique:user,email,'. $user_id. ',userId,deleted_at,NULL'

Here 4th parameter has to be the Auto-Increment Id of the Table. After that we can have Field-Value pairs. Here we have one, but we can multiple Field-value pairs like below:

'email' => 'unique:user,email,'. $user_id. ',userId,deleted_at,NULL,active,1'





No comments:

Post a Comment