Topics Eloquent ORM Eloquent Scopes & Querying
intermediate 16 min read

Eloquent Scopes & Querying

Local and global scopes, query builders, advanced where clauses, and Laravel 13 whereAny.

Local Scopes

use Illuminate\Database\Eloquent\Builder;

class User extends Model
{
public function scopeActive(Builder $query): void
{
$query->where("is_active", true);
}

public function scopeByRole(Builder $query, string $role): void
{
$query->whereHas("roles", fn($q) => $q->where("name", $role));
}

public function scopeRecentlyOnline(Builder $query): void
{
$query->where("last_active_at", ">=", now()->subMinutes(5));
}
}

// Usage
$admins = User::active()->byRole("admin")->get();
$online = User::recentlyOnline()->get();

Global Scopes

use Illuminate\Database\Eloquent\Attributes\ScopedBy;

#[ScopedBy([ActiveScope::class])]
class User extends Model { }

// Or in booted()
protected static function booted(): void
{
static::addGlobalScope("active", function (Builder $builder) {
$builder->where("is_active", true);
});
}

Advanced Where Clauses

// Where in relation exists
$users = User::whereHas("posts", fn($q) => $q->where("is_published", true))->get();

// Where in relation missing
$users = User::whereDoesntHave("posts")->get();

// Nested where
$items = Post::where(function (Builder $q) {
$q->where("title", "like", "%Laravel%")
->orWhere("body", "like", "%Laravel%");
})->get();

// Laravel 13: whereAny
$items = Post::whereAny(["title", "body"], "like", "%Laravel%")->get();

Examples

<?php
use App\Models\Post;

// Laravel 13: Search across multiple columns
\$results = Post::whereAny(
    ['title', 'body', 'excerpt'],
    'like',
    '%Laravel 13%'
)->get();

echo \$results->count() . ' posts found.';

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.