Scope là các ràng buộc query có thể tái sử dụng. Local scope trong model: public function scopeActive($query) { return $query->where("active", true); } rồi dùng User::active()->get(). Global scope áp dụng tự động, implement GlobalScope: hữu ích cho soft delete. Scope giảm trùng lặp và tăng khả năng đọc.
Ví dụ: thay vì viết User::where("active", true)->where("age", ">", 18)->get() ở nhiều nơi, tạo scopeAdults() và scopeActive() rồi chain User::active()->adults()->get(). Scope giữ query DRY và đóng gói business logic trong model.
Scopes are reusable query constraints. Local scope in model: public function scopeActive($query) { return $query->where("active", true); } then use User::active()->get(). Global scope applied automatically, implement GlobalScope: useful for soft deletes. Scopes reduce duplication and improve readability.
Example: instead of User::where("active", true)->where("age", ">", 18)->get() everywhere, create scopeAdults() and scopeActive() then chain User::active()->adults()->get(). Scopes keep queries DRY and encapsulate business logic in models.