Laravel Eloquent: Implementing Soft Deletes with Custom Logic

Laravel Eloquent: Implementing Soft Deletes with Custom Logic

Laravel Eloquent Soft Deletes with Custom Logic

Introduction to Soft Deletes

In Laravel, Eloquent provides a convenient way to implement soft deletes, which allows you to mark records as deleted without actually removing them from the database. This can be useful for maintaining a record of all changes made to the data, including deletions.

Default Soft Delete Behavior

By default, Laravel's soft delete feature uses a deleted_at timestamp to mark records as deleted. When a record is soft deleted, the deleted_at timestamp is set to the current time, and the record is no longer included in query results.

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

Implementing Custom Soft Delete Logic

To implement custom soft delete logic, you can override the runSoftDelete method on your Eloquent model. This method is called when a record is soft deleted, and allows you to perform custom actions before the record is marked as deleted.

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;

class User extends Model
{
    use SoftDeletes;

    public function runSoftDelete()
    {
        // Custom logic before soft delete
        $this->email = 'deleted-' . $this->email;
        parent::runSoftDelete();
    }
}

Restoring Soft Deleted Records

To restore a soft deleted record, you can use the restore method on the model instance. This will set the deleted_at timestamp to null, and the record will be included in query results again.

$user = User::withTrashed()->find(1);
$user->restore();

Conclusion

In this article, we've seen how to implement soft deletes with custom logic in Laravel Eloquent. By overriding the runSoftDelete method, you can perform custom actions before a record is marked as deleted, and by using the restore method, you can restore soft deleted records.

Selim Görmüş
Written by
Selim Görmüş

0 Comments

Share your thoughts

Your email address will not be published. Required fields are marked *

To leave a comment, please sign in to your account.