Beginner LevelLaravel
How do Soft Deletes work in Eloquent models?
❓ Interview Prompt: Explain SoftDeletes trait, deleted_at column, withTrashed(), onlyTrashed(), and restore() methods.
Soft deleting sets a 'deleted_at' timestamp on model records instead of executing an immediate SQL DELETE query.
Implementation:
1
Add 'use SoftDeletes;' trait to Eloquent model.
2
Include '$table->softDeletes();' column in migration.
Querying:
•
Soft deleted records are automatically excluded from normal Eloquent queries.
•
Include trashed records: 'User::withTrashed()->get()'
•
Restore soft deleted record: '$user->restore()'
Code Implementation Example
php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
class Customer extends Model
{
use SoftDeletes;
}
// Restoring a soft-deleted customer
Customer::withTrashed()->find(42)->restore();💡Eloquent Model using SoftDeletes trait and restore operation.
🎯 Interview Key Takeaway
Use SoftDeletes trait to preserve record audit histories while excluding deleted records from standard queries.
#Soft Deletes#Eloquent#Database#Beginner
Back to all Laravel Questions→