0
0
LaravelHow-ToBeginner · 3 min read

How to Use Scope in Eloquent: Simple Guide with Examples

In Laravel Eloquent, you use scopes to define reusable query logic inside your model by adding methods prefixed with scope. You call these scopes as query methods without the prefix, like User::active(), to filter or modify queries cleanly.
📐

Syntax

A scope method in an Eloquent model starts with the prefix scope followed by a descriptive name. It always receives a $query parameter representing the current query builder instance. You define your query constraints inside this method and return the modified query.

When calling the scope, you omit the scope prefix and use camelCase or snake_case as a normal method on the model's query.

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

// Usage:
User::active()->get();
💻

Example

This example shows a User model with a scope named active that filters users with active column set to 1. Calling User::active()->get() returns only active users.

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

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

// Usage in controller or elsewhere:
$activeUsers = User::active()->get();

foreach ($activeUsers as $user) {
    echo $user->name . "\n";
}
Output
John Doe Jane Smith
⚠️

Common Pitfalls

  • Forgetting to prefix the scope method with scope in the model causes it not to be recognized as a scope.
  • Calling the scope method with the scope prefix (e.g., User::scopeActive()) will cause an error; always call without the prefix.
  • Not returning the query builder instance from the scope method breaks query chaining.
php
<?php
// Wrong: Missing 'scope' prefix
public function active($query) {
    return $query->where('active', 1);
}

// Wrong: Calling with prefix
User::scopeActive()->get();

// Correct:
public function scopeActive($query) {
    return $query->where('active', 1);
}

User::active()->get();
📊

Quick Reference

ConceptDescriptionExample Usage
Scope MethodMethod in model prefixed with 'scope' to define query logicpublic function scopeActive($query) { ... }
Calling ScopeCall scope without 'scope' prefix on model queryUser::active()->get()
Return ValueAlways return the modified query builderreturn $query->where('active', 1);
ParametersFirst parameter is always the query builder instancescopeActive($query)
Multiple ScopesChain multiple scopes for complex queriesUser::active()->verified()->get()

Key Takeaways

Define scopes in models with methods prefixed by 'scope' and return the query builder.
Call scopes without the 'scope' prefix as query methods on the model.
Always return the query builder from your scope to allow chaining.
Use scopes to keep query logic reusable and clean.
Avoid calling scope methods with the 'scope' prefix or missing it in the model.