Local scopes encapsulate reusable query conditions.
class Order extends Model
{
public function scopePaid($query)
{
return $query->where('status', 'paid');
}
}
Usage:
$orders = Order::paid()->latest()->get();
Parameterized scope:
public function scopeStatus($query, $status)
{
return $query->where('status', $status);
}
Usage:
Order::status('pending')->get();
Real-project scenario
Instead of repeating:
where('status', 'active')
throughout controllers, repositories, and services, I can define:
User::active()->get();
This keeps business query logic reusable.
0 comments:
Post a Comment
Thanks