Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TimiAde's avatar

Soft Deleted Models

please can anyone explain soft deleted models, didnt really get it in the documentation

0 likes
2 replies
LaryAI's avatar
Level 58

Soft deleted models refer to a feature in Laravel that allows you to "soft delete" records from your database instead of permanently deleting them. This means that when you delete a record, it is not immediately removed from the database, but rather marked as deleted by setting a timestamp in the deleted_at column.

To use soft deleted models in Laravel, you need to perform the following steps:

  1. Add a deleted_at column to your database table. You can do this by creating a new migration or modifying an existing one. For example, if you have a users table, you can add the deleted_at column like this:
Schema::table('users', function (Blueprint $table) {
    $table->softDeletes();
});
  1. In your model class, use the SoftDeletes trait and specify the deleted_at column. For example, if you have a User model, you can add the SoftDeletes trait like this:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}
  1. Now, when you delete a record using the delete() method on a model instance, it will be soft deleted. For example:
$user = User::find(1);
$user->delete();
  1. To retrieve soft deleted records, you can use the withTrashed() method on your query. For example, to retrieve all users, including soft deleted ones:
$users = User::withTrashed()->get();
  1. To retrieve only soft deleted records, you can use the onlyTrashed() method on your query. For example, to retrieve all soft deleted users:
$users = User::onlyTrashed()->get();
  1. To restore a soft deleted record, you can use the restore() method on a model instance. For example, to restore a soft deleted user:
$user = User::withTrashed()->find(1);
$user->restore();

That's it! Soft deleted models provide a convenient way to handle deleted records without permanently removing them from the database.

tisuchi's avatar

@timiade Soft deleting is a feature in Laravel's Eloquent ORM where records are marked as deleted but not actually removed from the database. Instead, a deleted_at timestamp is set. This allows you to retrieve and restore "deleted" records later if needed.

Check the details example in @laryai answer.

1 like

Please or to participate in this conversation.