How to Create and Use Query Scope in Laravel 10 Eloquent

Query scopes are a great way to add additional functionality to your Eloquent models in Laravel. They allow you to define a set of conditions that can be applied to a query, making it easier to reuse the same query logic in multiple places.

1. Create the Scope

The first step is to create the scope. This is done by adding a method to your Eloquent model. The method should start with the word “scope” followed by the name of the scope. The method should accept a single parameter, which is an instance of the Eloquent query builder.

For example, if you wanted to create a scope to retrieve only active users, you could do something like this:

public function scopeActive($query)
{
return $query->where(‘active’, true);
}

2. Use the Scope

Once the scope has been created, you can use it in your Eloquent queries. To do this, you simply call the scope method on the query builder instance.

For example, if you wanted to retrieve all active users, you could do something like this:

$users = User::active()->get();

You can also chain multiple scopes together to create more complex queries. For example, if you wanted to retrieve all active users who have logged in within the last week, you could do something like this:

$users = User::active()->lastWeek()->get();

If you are working on a Laravel web application. And you do not know about query scope, how query scope is made, and how to use it. So today you will learn this here. So, In this tutorial, you will learn how to create and use query scopes, with laravel eloquent model, relationship, and join.

Query scopes are defined as methods within an Eloquent model class and are typically prefixed with the word “scope”. By convention, Laravel automatically recognizes these methods as query scopes and applies them when chaining methods on a query builder instance.

How to Create and Use Query Scope in Laravel Eloquent

Do you know that the query scope is created in Laravel. It can also use query scope with models, relationships and joins. you can see below

  • Create and Use Basic Query Scope in Model
  • Laravel 10 Create Dynamic Scope in Model
  • Laravel 10 Apply Scope with Relationship

Create and Use Basic Query Scope in Model

Now, you will learn how to create and use scope in your laravel model. You could do like:

Go to app/Post.php and create a scope here:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
	public $table = "posts";
      
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id', 'title', 'body', 'status'
    ];
    /**
     * Scope a query to only include popular users.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */

    public function scopeStatus($query)
    {
        return $query->where('status', 1);
    }
}

Use Basic Query Scope on Controller:

You could use model query scope in your laravel web application controllers, like following:

Post::status()->get(['id','title']);

In this example, the “active” query scope is applied to the Post model, resulting in a query that fetches only active users.

Laravel 10 Create Dynamic Scope in Model

Next, You will learn how to create and use dynamic query scope in laravel web application.

You can create dynamic query scopes in laravel model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
	public $table = "posts";
      
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id', 'title', 'body', 'status'
    ];
    /**
     * Scope a query to only include popular users.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeStatus($query, $type)
    {
        return $query->where('status', $type);
    }
}

Dynamic Scope Query On Controller

You could use dynamic model query scope in your laravel web application controllers like:

Post::status(1)->get(['id',title']);

Here, the “status” query scope allows you to retrieve posts with a specific status, such as “1.”

Laravel 10 Apply Scope with Relationship

Let’s use the following example for how to use query scopes with laravel relationships.

Let’s say you have two tables, categories and posts, and they are related through a one-to-many relationship where a category can have multiple posts. Here’s an example of how you can define a query scope in the Category model to retrieve categories along with their related posts:

class Category extends Model
{
    public function scopeWithPosts($query)
    {
        return $query->with('posts');
    }
}

In the above code, to define a query scope named “withPosts” that uses the with() method to eager load the related posts for each category.

To use this query scope, you can chain it onto a query builder instance when querying the Category model:

$categories = Category::withPosts()->get();

This code will retrieve all categories along with their related posts.

You can access the posts for a specific category like this:

$category = Category::withPosts()->find($categoryId);
$posts = $category->posts;

In this example, to find a category by its ID and eager load its related posts. Then, =access the posts relationship to retrieve the associated posts for that category.

Conclusion

In conclusion, Laravel query scopes are a powerful feature that allows you to define reusable query constraints within your model classes. By encapsulating common query logic into methods prefixed with “scope,” you can easily apply these constraints to query builder instances. Query scopes enhance code reusability, readability, and maintainability by centralizing query logic and making it more accessible throughout your application. They are a valuable tool for building expressive and efficient database queries in Laravel.

Recommended Laravel Posts

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?