Mastering Laravel Scope — A Comprehensive Guide with Code Examples

ArjunAmrutiya
4 min readJul 28, 2023

Introduction:
Laravel Scope is a powerful feature within Laravel’s Eloquent ORM that allows developers to define reusable query constraints. By leveraging Laravel Scopes, you can create cleaner, more efficient code and optimize database queries. In this comprehensive guide, we will explore various aspects of Laravel Scopes and demonstrate how to implement them effectively in your web applications.

1. Implementing Local Scopes in Laravel Eloquent

Local scopes allow you to encapsulate common query logic directly within your Laravel Eloquent models. By creating local scopes, you can easily apply specific constraints to your database queries, making your code more readable and maintainable.

Example:

Scope by Status: Implement a local scope to retrieve only active users from the database.

// User.php (Eloquent Model)

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

// Usage:
$activeUsers = User::active()->get();

Scope by Category: Create a scope to fetch products belonging to a specific category.

// Product.php (Eloquent Model)

public function scopeByCategory($query, $categoryId)
{…

--

--

ArjunAmrutiya
ArjunAmrutiya

Written by ArjunAmrutiya

👋 Hey there! I'm Arjun Amrutiya, a passionate web developer and blogger who loves all things PHP, Laravel and Vue.js. Welcome to my Medium account!

No responses yet