January 12th, 2023

laravel-query-scopes.png

Laravel Query Scopes

One of the features that Laravel provides is the ability to use "scopes" when querying data from the database. In this article, we'll take a closer look at what query scopes are, and how you can use them in your Laravel application.

A query scope is a way to encapsulate a common set of constraints that you may want to apply to a query, and reuse that logic across multiple parts of your application. Scopes can be used to filter, sort, or otherwise modify the data returned by a query, and can be easily chained together to build complex queries.

To create a new query scope, you can use the scope method on a model. For example, you can create a scope that only returns records where the status column is set to published:

1class Post extends Model
2{
3 public function scopePublished($query)
4 {
5 return $query->where('status', 'published');
6 }
7}

Once you've defined a scope, you can use it in any query by chaining the scope method onto the query builder. For example, you can retrieve all published posts by calling Post::published()->get().

You also can use with parameter to pass values to your scope, like this:

1class Post extends Model
2{
3 public function scopePublished($query, $status)
4 {
5 return $query->where('status', $status);
6 }
7}

You can use this scope like this:

1$publishedPosts = Post::published("published")->get();

You also can use multiple scopes in same query, it will add all conditions to the query. For example:

1$publishedPostsWithTitle = Post::published("published")->withTitle("Laravel Query Scope")->get();

Query Scopes can help you to keep your code clean and organized. It also makes it easy to change the underlying logic of your queries without having to update the code in multiple places. You can use it for complex filtering and searching, you can also make your scope global to use it from everywhere in your project.

In conclusion, query scopes are a powerful tool that can help you to write more maintainable and organized code in your Laravel applications. They allow you to encapsulate common query logic and reuse it throughout your application, helping to keep your codebase organized and easy to understand.

fathom analytics Follow @LaravelMagazine on Twitter →

Comments

Marian Pop

PHP / Laravel Developer. Writing and maintaining @LaravelMagazine. Host of "The Laravel Magazine Podcast". Pronouns: vi/vim.

Newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox every Friday!

We'll never share your email address and you can opt out at any time.