DEV Community

AJ
AJ

Posted on • Originally published at Medium

Laravel Local Scopes

1. Introduction to Laravel Scopes

Laravel Scope is one of the best features of Laravel, it is a querying method in which we can create a scope in a model or a new class. It is a powerful tool to help you write reusable and maintainable code.

How To Integrate Scopes.

$activeUser = Post::where('active', true)->get();
Enter fullscreen mode Exit fullscreen mode

But I want to get Active User, Again and Again, So right now I need to write this query again and again and it will show duplication and not a standard way. So Here is the Solution in Scope.

class User extends Model
{    
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
}
Enter fullscreen mode Exit fullscreen mode

In This picture.

  • User is a model class that encapsulates the model data.
  • It has a method called scopeActive.
  • ScopeActive adds a filter to the database Query and ensures that only active users are returned from a database.
  • It is recommended that the scope method name be started with a lowercase letter.
  • Now we can use this function to filter out data related to the user in a controller.
$activeUser = User::active()->get();
Enter fullscreen mode Exit fullscreen mode

How To Use Dynamic Scopes.
If we want to use Scope Dynamically, we need to pass the parameter for this scope.

class User extends Model
{
  public function scopeActive($query,$value)
    {
        return $query->where('active', $value);                
        //there is another way also to call this 
        //return $query->whereActive($value);    
    }
}
Enter fullscreen mode Exit fullscreen mode

Now we can use dynamic Scope just like this.

$activeUser = User::active(true)->get();
Enter fullscreen mode Exit fullscreen mode

How To Use Scopes with Relations.

A scope can also be defined in the relation model.

class User extends Model
{
  public function scopePosts($query,$value)
    {
        return $query->with('posts');                
    }
}
Enter fullscreen mode Exit fullscreen mode

We can then use this scope to retrieve all posts for a specific user:

$user = User::find(1);

$posts = $user->posts()->get();
Enter fullscreen mode Exit fullscreen mode

How To Use Scopes with Joins.

We can use Scope with joins also.. For example, if you have a model called Order that belongs to a User, and you want to retrieve all orders for a user that have a total greater than $100, you can use a scope that joins the Order model and applies a where clause to the resulting query:

public function scopeTotalGreaterThan($query, $amount) {

    return $query->join('orders', 'users.id', '=', 'orders.user_id')

    ->where('orders.total', '>', $amount);

}
Enter fullscreen mode Exit fullscreen mode

You can then use this scope to retrieve all users with orders that have a total greater than $100:

$users = User::totalGreaterThan(100)->get();
Enter fullscreen mode Exit fullscreen mode

Best Practices for Implementing Laravel Scopes

6 Best Practices for Implementing Laravel Scopes
Implementing Laravel scopes requires attention to detail and best practices to ensure that the code runs smoothly and effectively. Here are six best practices for implementing Laravel scopes in your projects:

  1. Choose the Right Scope Name - The scope name should reflect the exact behavior of the query. A descriptive and concise name makes it easier to understand the purpose of the scope.
  2. Use Scopes Sparingly - Too many scopes can make your code hard to maintain. Consider using scopes only when you expect to reuse the code repeatedly.
  3. Keep it Atomic - Each scope should contain only one specific query constraint. This helps to maintain the clarity and readability of your code.
  4. Use Query Builder Constraints - Laravel scopes can use all the query builder constraints available in Laravel. This includes where clauses, joins, and limits.
  5. Use Local Scopes - Local scopes are defined inside a model and can be used within the model for filtering or querying. This helps to maintain clean and concise code.
  6. Test Your Scopes - Testing is important to ensure that your code works as expected. Create unit tests to verify that the scope is filtering the query correctly. By following these practices, you can implement Laravel scopes effectively and efficiently in your projects. Laravel scopes are a powerful tool that can help you achieve consistent, secure, and reusable database queries in your Laravel applications.

Thanks
And if you love the content and want to support more awesome articles, consider buying me a coffee! ☕️🥳 Your support means the world to me and helps keep the knowledge flowing. You can do that right here: 👉 Buy Me a Coffee

Image description

Top comments (0)