Soft Deletes in Laravel allow you to mark records as deleted without permanently removing them from the database. This feature is useful for retaining data while hiding it from active queries.
Soft Deletes were introduced to help developers manage data retention without requiring manual archive tables or processes. It leverages an additional deleted_at
column in the database to track deletion timestamps.
onlyTrashed
and withTrashed
scopes to manage soft-deleted records.To enable soft deletes on a model, add the SoftDeletes
trait:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
When deleting a record, Laravel sets the deleted_at
column instead of removing the record:
$post = Post::find(1);
$post->delete();
To restore a soft-deleted record:
Post::withTrashed()->find(1)->restore();
To permanently delete a soft-deleted record:
Post::onlyTrashed()->find(1)->forceDelete();
This approach ensures that data is retained safely while allowing flexibility for retrieval or permanent removal.