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.
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 .
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.
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.
You can validate passing extra conditions:
'unique:users,deleted_at,NULL'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With