How to check if row is soft-deleted in Eloquent?

PhpLaravelEloquentLaravel 5.1Soft Delete

Php Problem Overview


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()) { ... }

Php Solutions


Solution 1 - Php

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()) { ... }

Solution 2 - Php

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!

Solution 3 - Php

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);

Solution 4 - Php

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...
}

Solution 5 - Php

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');
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDisgruntledGoatView Question on Stackoverflow
Solution 1 - PhpDisgruntledGoatView Answer on Stackoverflow
Solution 2 - Phpprotanvir993View Answer on Stackoverflow
Solution 3 - PhpErik CampobadalView Answer on Stackoverflow
Solution 4 - Phpmajeed mohammadianView Answer on Stackoverflow
Solution 5 - PhpPri NceView Answer on Stackoverflow