Category : Laravel Feature Publish At : 09 Apr, 2025
Scopes make it easy to reuse parts of your database queries in your models. To create one, just add the word "scope" to the beginning of a method in your model.
How to define Scope?
Below example of Currency model. Now, you want to fetch the active currency at front-end and then no need to write every time with "where" conditions. You can define the scope method and reuse everytime along with the Model.
class Currency extends Model
{
use HasUlids, SoftDeletes;
protected $table = 'currencies';
public $fillable = [
'title',
'symbol',
'country',
'is_active',
];
public function scopeIsActive($query)
{
return $query->whereIsActive(1);
}
}
How to Use?
$currency = Currency::isActive()->orderBy('created_at')->get();
More Info about Query Scope visit,