'Laravel 4 - how to use a unique validation rule / unique columns with soft deletes?

Assume, you are trying to create a new user, with a User model ( using soft deletes ) having a unique rule for it's email address, but there exists a trashed user within the database.

When trying to validate the new user's data, you will get a validation error, because of the existing email.

I made some kind of extra validation within my Controllers, but wouldn't it be nice to have it all within the Model?

Would you suggest creating a custom validation rule?

As I haven't found a clean solution now, I am interessted in how others solved this problem.



Solution 1:[1]

You can validate passing extra conditions:

'unique:users,deleted_at,NULL'

Solution 2:[2]

This is the best approach

        'email' => 'required|email|unique:users,email,NULL,id,deleted_at,NULL',

It give you this query

select count(*) as aggregate from `users` where `email` = ? and `deleted_at` is null

Solution 3:[3]

Laravel offers "Additional Where Clauses".

My url validation rule (from the update model method) looks like this:

$rules['url'] = 'required|unique:pages,url,'.$page->id.',id,deleted_at,NULL';

This means that the url must be unique, must ignore the current page and ignore the pages where deleted_at id not NULL.

Hope this helps.

Solution 4:[4]

Your Eloquent model should have the $softDeletes property set. If so, then when you perform a WHERE check, like User::where('username', 'jimbob'), Eloquent will automatically add in the query WHERE deleted_at IS NULL... which excludes soft deleted items.

Solution 5:[5]

In laravel 6.2+ you can use

'email' => ['required', Rule::unique('users')->whereNull('deleted_at')]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriel Koerich
Solution 2 Cesar Alonso
Solution 3 adrianthedev
Solution 4 Rob W
Solution 5 zardoz