Reputation: 72570
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()) { ... }
Upvotes: 76
Views: 58711
Reputation: 83
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...
}
Upvotes: 3
Reputation: 711
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');
}
Upvotes: 0
Reputation: 917
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);
Upvotes: 6
Reputation: 3109
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!
Upvotes: 8
Reputation: 72570
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()) { ... }
Upvotes: 130