0
0
Laravelframework~5 mins

Query scopes in Laravel

Choose your learning style9 modes available
Introduction

Query scopes help you reuse common database query parts easily. They keep your code clean and simple.

You want to filter users who are active in many places in your app.
You need to reuse a common condition like 'only published posts' in different queries.
You want to keep your database queries organized inside your model.
You want to avoid repeating the same query code in multiple controllers or views.
Syntax
Laravel
public function scopeName($query, $param1, $param2)
{
    return $query->where(...);
}
Scope methods always start with 'scope' followed by the scope name with first letter uppercase.
When using the scope, call it without the 'scope' prefix, like Model::name($params).
Examples
This scope filters records where the 'active' column is 1.
Laravel
public function scopeActive($query)
{
    return $query->where('active', 1);
}
This scope filters records by a given type passed as a parameter.
Laravel
public function scopeOfType($query, $type)
{
    return $query->where('type', $type);
}
Sample Program

This example shows a User model with two query scopes: active and role. You can call these scopes to filter users easily. The example prints the SQL queries generated by these scopes.

Laravel
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // Scope to get only active users
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }

    // Scope to get users by role
    public function scopeRole($query, $role)
    {
        return $query->where('role', $role);
    }
}

// Usage example in a controller or elsewhere
$activeUsers = User::active()->get();
$adminUsers = User::role('admin')->get();

// For demonstration, we print the SQL queries generated

echo $activeUsers->toSql() . "\n";
echo $adminUsers->toSql() . "\n";
OutputSuccess
Important Notes

Query scopes keep your queries DRY (Don't Repeat Yourself).

Scopes can accept parameters to make them flexible.

Use scopes to improve readability and maintainability of your code.

Summary

Query scopes let you reuse common query parts inside your model.

Define scopes with methods starting with 'scope' and call them without that prefix.

Scopes can take parameters to customize the query.