Soft deletion in Laravel enables you to designate entries as removed without permanently removing them from the database. This functionality is great for storing data while keeping it out of active searches, ensuring flexibility and data recoverability.
Soft deletion was added in Laravel to simplify data retention and recovery by eliminating the requirement for separate archive tables or manual methods. It works by creating a deleted_at column in the database that stores the timestamp of a soft delete.
onlyTrashed and withTrashed, to efficiently handle soft-deleted data.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();