72

In Laravel 5.1 is there a nice way to check if an eloquent model object has been soft-deleted? I'm not talking about selecting data but once I have the object e.g. Thing::withTrashed()->find($id)

So far the only way I can see is

if ($thing->deleted_at !== null) { ... }

I do not see any relevant method in the API that would allow for example

if ($thing->isDeleted()) { ... }
DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290

5 Answers5

124

Just realised I was looking in the wrong API. The Model class doesn't have this, but the SoftDelete trait that my models use has a trashed() method.

So I can write

if ($thing->trashed()) { ... }
DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290
  • Maybe 5.2 is different, but I tried this and it didn't work. Instead when I tried getting $thing where it was soft deleted, Laravel returned back null, so I just checked `if ($thing == null)` – Zachary Weixelbaum Mar 27 '17 at 14:19
  • 1
    @ZacharyWeixelbaum Did you use `withTrashed()` to fetch the item, as I mentioned in the question? Otherwise you won't get any deleted records. – DisgruntledGoat Mar 27 '17 at 20:51
8

In laravel6, you can use followings.

To check the Eloquent Model is using soft delete:

if( method_exists($thing, 'trashed') ) {
    // do something
}

To check the Eloquent Model is using soft delete in resource (when using resource to response):

if( method_exists($this->resource, 'trashed') ) {
    // do something
}

And finally to check if the model is trashed:

if ($thing->trashed()) {
    // do something
}

Hope, this will be helpful!

protanvir993
  • 2,759
  • 1
  • 20
  • 17
5

For those seeking an answer on testing environment, within laravel's test case you can assert as:

$this->assertSoftDeleted($user);

or in case it's just deleted (without soft deleting)

$this->assertDeleted($user);
Erik Campobadal
  • 867
  • 9
  • 14
2

This is the best way

$model = 'App\\Models\\ModelName';

$uses_soft_delete = in_array('Illuminate\Database\Eloquent\SoftDeletes', class_uses($model));

if($usesSoftDeletes) {
    // write code...
}
0

This worked for me

$checkDomain = Domain::where('tenant_id', $subdomain)->withTrashed()->first();
                
 if($checkDomain->trashed()){
       return redirect()->route('domain.not.found');
 }else{
     return view('frontend.' . theme() . '.index');
 }
Pri Nce
  • 576
  • 6
  • 18