What are query scopes?
What are query scopes?
Query scopes in Laravel are a powerful feature of the Eloquent ORM that allow developers to encapsulate common query logic within model methods. These scopes can be reused throughout the application, making the code more readable and maintainable.
Local Scopes:
scope
by convention.class Post extends Model {
public function scopeActive($query) {
return $query->where('active', 1);
}
}
$activePosts = Post::active()->get();
Dynamic Scopes:
class Post extends Model {
public function scopeStatus($query, $status) {
return $query->where('status', $status);
}
}
$publishedPosts = Post::status('published')->get();
Global Scopes:
class Post extends Model {
protected static function boot() {
parent::boot();
static::addGlobalScope('active', function (Builder $builder) {
$builder->where('active', 1);
});
}
}
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào