Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 463
Remluben Avatar asked Jul 03 '13 21:07

Remluben


People also ask

How would you implement soft delete in laravel with example?

To soft delete a model you may use: $model = Contents::find( $id ); $model->delete(); Deleted (soft) models are identified by the timestamp and if deleted_at field is NULL then it's not deleted and using the restore method actually makes the deleted_at field NULL .

What is soft deleting in laravel?

Soft deleting the data allows us to easily view and restore the data with minimal work and can be a huge time saver when data is accidentally deleted. Laravel provides support for soft deleting using the Illuminate\Database\Eloquent\SoftDeletes trait.

Is unique validation in laravel?

To add the unique validation in laravel migration, you have to tell the laravel that field will be unique. And you can do this by the unique() method. This case prompt, when you know that field will be unique in the database and no user will have the same data twice.


2 Answers

You can validate passing extra conditions:

'unique:users,deleted_at,NULL'
like image 137
Gabriel Koerich Avatar answered Sep 29 '22 02:09

Gabriel Koerich


This sounds like an issue with your business logic rather than a technical problem.

The purpose of a soft delete is to allow for the possibility that the soft-deleted record may be restored in the future. However, if your application needs uniqueness of email (which is completely normal), you wouldn't want to both create a new user with that email address and be able to restore the old one as this would contravene the uniqueness requirement.

So if there is a soft deleted record with the email address for which you are adding as a new record, you should consider instead restoring the original record and applying the new information to it as an update, rather than trying to circumvent the uniqueness check to create a new record.

like image 27
petercoles Avatar answered Sep 29 '22 03:09

petercoles