Table of Contents
What is Eloquent query scope?
How to define and use Local Scopes
Common application scenarios include:
How to use Parameterized Scopes
What should I pay attention to when using Global Scopes?
A little trick: combine multiple scopes
Home PHP Framework Laravel Using Eloquent Query Scopes in Laravel.

Using Eloquent Query Scopes in Laravel.

Jul 29, 2025 am 01:19 AM
laravel eloquent

Eloquent query scope improves code clarity and reusability by encapsulating common query logic. 1. The local scope is defined with methods starting with scope, such as scopeActive() is used to filter enabled users; 2. The dynamic scope supports parameter passing, such as scopeStatus($status) to achieve flexible state filtering; 3. The global scope is automatically applied to all queries, suitable for data isolation but needs to be used with caution; 4. Multiple scopes can be combined in chains to enhance semantic expression and maintenance; 5. Complex queries can be centrally processed through conditional judgments to improve flexibility.

Using Eloquent Query Scopes in Laravel.

In Laravel, Eloquent Query Scopes is a very practical but often underestimated feature. It can help you encapsulate commonly used query logic, making the code clearer and more reusable. If you often write duplicate where conditions or want to organize query logic in your model, using Query Scopes is a good choice.

Using Eloquent Query Scopes in Laravel.

What is Eloquent query scope?

Simply put, the Eloquent query scope is a method defined in the model to add some common query conditions. You can understand it as a "preset filter". Every time this scope is called, the query conditions you defined will be automatically added.

For example, if you want to filter out all users with status enabled, you can define an active() scope, so that when checking active users in the future, you don’t have to write where('status', 1) every time.

Using Eloquent Query Scopes in Laravel.

How to define and use Local Scopes

Defining a local scope is simple, you just need to create a method starting with scope in the model.

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

Then you can use it like this:

Using Eloquent Query Scopes in Laravel.
 User::active()->get();

Note: The first parameter to the scope must be $query , representing the current query builder.

Common application scenarios include:

  • Filter published content: scopePublished()
  • Filter the records marked as soft deleted: scopeNotDeleted()
  • Query by time range: scopeLastWeek()

How to use Parameterized Scopes

Sometimes you want the scope to receive parameters. For example, not only to check the user with "status 1", but also want to pass in different status values.

This can be done at this time:

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

Pass parameters when using:

 User::status(2)->get();

This method is very suitable for scenarios where flexible value transfer is required, such as search by keyword, pagination offset, time interval, etc.


What should I pay attention to when using Global Scopes?

In addition to local scopes, Laravel supports global scopes, which are automatically applied every time the model is queryed. Suitable for unified data isolation, such as only access to the current tenant's data in a multi-tenant system.

To use global scope, you need to create a class to implement Illuminate\Database\Eloquent\Scope interface, and then call addGlobalScope() in booted() method of the model.

 protected static function booted()
{
    static::addGlobalScope('tenant', function ($builder) {
        $builder->where('tenant_id', tenant_current_id());
    });
}

However, it should be noted that once the global scope is added, it cannot be easily removed . If you want to bypass it temporarily, you can only cancel it by using withoutGlobalScopes() method.


A little trick: combine multiple scopes

You can combine multiple scopes like building blocks, such as:

 User::active()->verified()->recent()->get();

Each scope returns a query constructor instance, so it can be called in a chain. This writing is not only semantic, but also easy to test and maintain.

In addition, if a query is particularly complex, multiple conditional judgments can be encapsulated in one scope, such as:

 public function scopeFilter($query, $filters)
{
    if (! empty($filters['status'])) {
        $query->where('status', $filters['status']);
    }

    if (! empty($filters['search'])) {
        $query->where('name', 'like', '%' . $filters['search'] . '%');
    }
}

In this way, the filter parameters transmitted from the front end can be processed centrally.


Basically that's it. Query Scopes is not complicated, but is very useful in actual development. Using it rationally can make your model layer cleaner and easier to write consistent query logic.

The above is the detailed content of Using Eloquent Query Scopes in Laravel.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Beginner's Guide to RimWorld: Odyssey
1 months ago By Jack chen
PHP Variable Scope Explained
4 weeks ago By 百草
Tips for Writing PHP Comments
3 weeks ago By 百草
Commenting Out Code in PHP
3 weeks ago By 百草

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1509
276
What is Configuration Caching in Laravel? What is Configuration Caching in Laravel? Jul 27, 2025 am 03:54 AM

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

How to mock objects in Laravel tests? How to mock objects in Laravel tests? Jul 27, 2025 am 03:13 AM

UseMockeryforcustomdependenciesbysettingexpectationswithshouldReceive().2.UseLaravel’sfake()methodforfacadeslikeMail,Queue,andHttptopreventrealinteractions.3.Replacecontainer-boundserviceswith$this->mock()forcleanersyntax.4.UseHttp::fake()withURLp

How to implement a referral system in Laravel? How to implement a referral system in Laravel? Aug 02, 2025 am 06:55 AM

Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,

How to run a Laravel project? How to run a Laravel project? Jul 28, 2025 am 04:28 AM

CheckPHP>=8.1,Composer,andwebserver;2.Cloneorcreateprojectandruncomposerinstall;3.Copy.env.exampleto.envandrunphpartisankey:generate;4.Setdatabasecredentialsin.envandrunphpartisanmigrate--seed;5.Startserverwithphpartisanserve;6.Optionallyrunnpmins

How to seed a database in Laravel? How to seed a database in Laravel? Jul 28, 2025 am 04:23 AM

Create a seeder file: Use phpartisanmake:seederUserSeeder to generate the seeder class, and insert data through the model factory or database query in the run method; 2. Call other seeder in DatabaseSeeder: register UserSeeder, PostSeeder, etc. in order through $this->call() to ensure the dependency is correct; 3. Run seeder: execute phpartisandb:seed to run all registered seeders, or use phpartisanmigrate:fresh--seed to reset and refill the data; 4

How to build a REST API with Laravel? How to build a REST API with Laravel? Jul 30, 2025 am 03:41 AM

Create a new Laravel project and start the service; 2. Generate the model, migration and controller and run the migration; 3. Define the RESTful route in routes/api.php; 4. Implement the addition, deletion, modification and query method in PostController and return the JSON response; 5. Use Postman or curl to test the API function; 6. Optionally add API authentication through Sanctum; finally obtain a clear structure, complete and extensible LaravelRESTAPI, suitable for practical applications.

How to implement feature flags in a Laravel app? How to implement feature flags in a Laravel app? Jul 30, 2025 am 01:45 AM

Chooseafeatureflagstrategysuchasconfig-based,database-driven,orthird-partytoolslikeFlagsmith.2.Setupadatabase-drivensystembycreatingamigrationforafeature_flagstablewithname,enabled,andrulesfields,thenrunthemigration.3.CreateaFeatureFlagmodelwithfilla

What is Eloquent ORM in Laravel? What is Eloquent ORM in Laravel? Jul 29, 2025 am 03:50 AM

EloquentORM is Laravel's built-in object relational mapping system. It operates the database through PHP syntax instead of native SQL, making the code more concise and easy to maintain; 1. Each data table corresponds to a model class, and each record exists as a model instance; 2. Adopt active record mode, and the model instance can be saved or updated by itself; 3. Support batch assignment, and the $fillable attribute needs to be defined in the model to ensure security; 4. Provide strong relationship support, such as one-to-one, one-to-many, many-to-many, etc., and you can access the associated data through method calls; 5. Integrated query constructor, where, orderBy and other methods can be called chained to build queries; 6. Support accessors and modifiers, which can format the number when obtaining or setting attributes.

See all articles