How to check if row is soft-deleted in Eloquent?
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...
}
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!
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);
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()) { ... }