Streamlining Eloquent Queries: Mastering User Scopes and Global Scopes in Laravel

Haseeb MirzaHaseeb Mirza
3 min read

Intro

As a Laravel developer, I've found that user scopes and global scopes are incredibly useful tools for managing complex Eloquent queries. In this article, I'll walk you through how to leverage these features to make your code more efficient and easier to manage.

here's the project file and folder structure, along with a refined version of the article on user scopes and global scopes in Laravel:

Project File and Folder Structure

File & Folder Structure

User Scopes and Global Scopes in Laravel

In Laravel, scopes are a powerful way to add constraints to your Eloquent queries. They allow you to encapsulate common query logic and make your code more reusable and maintainable.

User Scopes

User scopes are methods defined within your Eloquent model classes that provide a convenient way to scope your queries. They are defined using the scope prefix followed by the name of the scope.

Here's an example of a user scope in a Post model:

public function scopePublished($query)
{
    return $query->where('published', true);
}

You can then use this scope in your controller or elsewhere in your application:

$posts = Post::published()->get();

This will retrieve all published posts.

Global Scopes

Global scopes are similar to user scopes, but they are automatically applied to all queries for a given model. They are defined by creating a class that implements the Illuminate\Database\Eloquent\Scope interface and defining the apply method.

Here's an example of a global scope that only retrieves posts that are published and not deleted:

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class PublishedAndNotDeletedScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('published', true)
                ->whereNull('deleted_at');
    }
}

To register this global scope, you need to add it to your model's booted method:

// In the Post model
protected static function booted()
{
    static::addGlobalScope(new PublishedAndNotDeletedScope);
}

Now, whenever you query the Post model, it will automatically include the constraints defined in the global scope.

Project Demo

In the provided project structure, you can find the following files and their purposes:

  1. PostController.php: This controller demonstrates the usage of user scopes and global scopes.

  2. Post.php: This is the Eloquent model for the posts table, which includes the user scope and the registration of the global scope.

  3. PublishedAndNotDeletedScope.php: This is the implementation of the global scope that retrieves published posts that are not deleted.

  4. 2023_05_29_000000_create_posts_table.php: This is the migration file that creates the posts table with the necessary columns. 5.2023_05_29_000001_create_published_and_not_deleted_scope.php: This is an optional migration file that can be used to create the global scope in the database.

  5. DatabaseSeeder.php: This seeder file can be used to populate the posts table with sample data.

  6. index.blade.php: This is a simple view that displays the list of posts.

To run the project, follow these steps:

  1. Clone the repository and navigate to the project directory.

  2. Install the dependencies using composer install.

  3. Create a new database and update the .env file with the database connection details.

  4. Run the migrations and seeders using the following commands:

php artisan migrate
php artisan db:seed
  1. Start the development server using php artisan serve.

  2. Visit http://localhost:8000/posts in your web browser to see the list of published posts.

This project demonstrates how user scopes and global scopes can be used to add constraints to your Eloquent queries, making your code more reusable and maintainable.

Happy coding :)

#LaravelDevelopment

#EloquentQueries

#QueryOptimization

#LaravelBestPractices

#EloquentScopes

#LaravelTips

Image Source

0
Subscribe to my newsletter

Read articles from Haseeb Mirza directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Haseeb Mirza
Haseeb Mirza

Web Dev | Passionate about driving small business success through digital innovation. Let's build, learn, and thrive in the world of bits and bytes! ๐Ÿš€๐Ÿ–ฅ๏ธ