AliAdams
2 years ago
379
11
Eloquent

If I have for example defined scopeActive(), how best should I test if an Eloquent object "is Active"?

Posted 2 years ago by AliAdams

Long time lurker, first time poster - hi!

This has been bugging me for a while - hopefully one of you guys will know the best way of doing this!

If I have defined a local scope such as 'active' is there a way to test whether a certain Eloquent Object is active without duplicating the logic used in the definition of the scope?

$active_widgets = Widget::active()->get(); // < using the scopeActive() to pull a list of active widgets is fine

$widget = Widget::find(1);

if( $widget->isActive() ){ // < What I'm trying to achieve
    echo 'Yay!';
} else {
    echo 'Awww...';
}

Ideally I'm looking for the most efficient way to do this without duplicating the code used to define the scope and without making an additional database query like:

 // In Widget class:

public function isActive(){
    return self::active()->where('id',$this->id)->count();
}

Please sign in or create an account to participate in this conversation.