Your Guide to Laravel Excellence

Learn Laravel Scopes and simplify Eloquent Queries

Learn Laravel Scopes and simplify Eloquent Queries

In this article we learn how to use Laravel scopes from scratch  which you can reuse in a query and you don’t need to duplicate . Scopes in laravel allow you to define reusable query constraints that can be applied to queries on your models.It made code more organized, readable.We have two types of scopes , Local Scope and Global Scope.

Creating a Scope (Local Scope)

You can define a scope by adding a method to your Eloquent model. The method name should start with scope, followed by a meaningful name describing the scope's purpose.

 class Post extends Model
{
   // Scope to retrieve only published posts
    public function scopePublished($query)
    {
        return $query->where('published', true);
    }
}

Using a Scope

We can use it like any other Eloquent method when querying your model.

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

Scopes can also accept parameters, allowing for dynamic behavior.

public function scopeStatus($query, $status)
{
    return $query->where('status', $status);
}
$draftPosts = Post::status('draft')->get();

Global Scopes

Global scopes automatically apply to all queries for a given model.

public static function booted()
{
    static::addGlobalScope('published', function ($query) {
        $query->where('published', true);
    });
}

Removing Scopes

if you need to temporarily remove a scope,this is how you can do that.

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

Recommeded Posts

Resize Images using intervention-image

Resize Images using intervention-image

Resize Images using intervention-image

4 months ago Read article →
Model Change Tracking in Laravel 11 - Laravel Auditing

Model Change Tracking in Laravel 11 - Laravel Auditing

Model Change Tracking in Laravel 11 - Laravel Auditing

4 months ago Read article →
Many-to-Many relationship in Laravel - All you need to know

Many-to-Many relationship in Laravel - All you need to know

how to implement many-to-many relationships in Laravel, including pivot tables, syncing data, and advanced queries. Learn best practices for optimizing database relationships using Laravel Eloquent. Perfect guide for developers to master Laravel many-to-many relationship

4 months ago Read article →
How to show old selected values in multiple select options in Laravel

How to show old selected values in multiple select options in Laravel

How to show old selected values in multiple select options in Laravel

4 months ago Read article →