2

i was made a model service trait to use with all models

some model use softDelete but some are not.

How i can check if model have softDeletes ability or not by checking if model contain column deleted_at or not

Here is my code to check

$isSoftDeleted = \Schema::hasColumn($model->getTable(), 'deleted_at');

is it a good way to do ?

Kotzilla
  • 1,333
  • 18
  • 27

2 Answers2

4

Another way of checking (a little bit more raw) is checking for the existence of method forceDelete.

METHOD 1 - Check if forceDelete method exists

if(method_exists($model, 'forceDelete')){
    // Do your stuff here
}

Again, this is a little hack.

METHOD 2 - Using an interface

Generally is not optimal to check if a model uses a trait using insanceof, technically speaking it would be more appropriate to create an interface UsesSoftDeletes and make the model that actually use the SoftDeletes trait implement it. Doing that you could simply make a check using instanceof operator.

An example:

interface UsesSoftDeletes{
    //
}

then in your model

class User extends Model implements UsesSoftDeletes
{

    use SoftDeletes;

}

Then check with

if($model instanceof UsesSoftDeletes){
    // Do your stuff here
}

EDIT - Checking for global scope

You can also check if the model uses the SoftDeletingScope class (Laravel 5.x).

if($model->hasGlobalScope('Illuminate\Database\Eloquent\SoftDeletingScope')){
 // Do your stuff
}
Desh901
  • 2,633
  • 17
  • 24
  • `$model->hasGlobalScope('Illuminate\Database\Eloquent\SoftDeletingScope')` working for me, thank you – Kotzilla Oct 12 '17 at 02:58
1

You can use class_uses_recursive(static::class) e.g.

$uses = class_uses_recursive(static::class);
return in_array(SoftDeletes::class, $uses);

Checking the column can only indicate that it exists, not that you're actually using the trait.

Note that class_uses_recursive is a Laravel helper function using the built-in class_uses but also ascending into parent classes.

apokryfos
  • 38,771
  • 9
  • 70
  • 114