HomeLARAVELWhat is withTrashed() and onlyTrashed()?

What is withTrashed() and onlyTrashed()?

In Laravel, withTrashed() and onlyTrashed() are methods used with Eloquent models that implement Soft Deletes. They allow you to query records that have been “soft deleted” (i.e., not permanently removed from the database, but marked as deleted). Let me break it down carefully.


1. Soft Deletes Basics

  • Normally, when you call $model->delete(), the record is removed from the database.
  • With Soft Deletes, Laravel adds a deleted_at column in the table.
  • When you “delete” a record, Laravel sets deleted_at to the current timestamp instead of actually deleting it.
  • Records with a non-null deleted_at are considered “trashed”.

Example migration for soft deletes:

Schema::table('users', function (Blueprint $table) {
    $table->softDeletes(); // adds deleted_at column
});

Enable Soft Deletes in model:

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

2. withTrashed()

  • Purpose: Retrieve all records, including soft-deleted ones.
  • By default, Eloquent ignores soft-deleted records.
  • Using withTrashed(), you can include them in your query.

Example:

$users = User::withTrashed()->get();
  • This will fetch all users, both active and soft-deleted.

3. onlyTrashed()

  • Purpose: Retrieve only the soft-deleted records.
  • This is useful if you want to see what has been “deleted” or maybe restore them.

Example:

$deletedUsers = User::onlyTrashed()->get();
  • This fetches only users whose deleted_at is not null.

4. Restore Soft Deleted Records

  • You can restore a soft-deleted record using restore().
$user = User::withTrashed()->find(1);
$user->restore(); // deleted_at becomes null
  • You can also force delete to permanently remove:
$user->forceDelete();

Summary Table:

MethodReturns
all() (default)Only non-deleted records
withTrashed()All records, including soft-deleted
onlyTrashed()Only soft-deleted records

Share: 

No comments yet! You be the first to comment.

Leave a Reply

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