In the Laravel Model Scope Example tutorial, you will learn how to create and use dynamic eloquent model query scopes in the Laravel 11 application. Laravel scope in the Model is easy to use eloquent query and get the data with mapping.
A scope is a method in your model that makes it able to add database logic into your model. Laravel provided us with two types of scopes for maintaining our queries with fast and the code easily reusable;
How to Use Query Scope in Laravel 11
Global scopes: Global scopes allow you to add constraints to all queries on a model. This way you make sure that every query on a given model has certain constraints. We will learn about global scope in the next topic;
Local Scopes: Local scopes make it able to define common sets of constraints that are easily reusable
Suppose, we are getting the users according to their status;
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class Usercontroller extends Controller
{
public function index()
{
$status = 2;
$users = User::where(['status', $status])->get();
return view('users', compact('users'));
}
}
Here you can see we are adding a where query for all time. To remove the queries, we can call Scope. below we create filter scope in User model and our query will be smoother and fast;
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens; // sanctum
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
public function scopeFilterByStatus($query, $status)
{
return $query->where(['status', $status]);
}
}
Laravel knows scope as an alias. After defining one or more local scopes they could be used by calling the scope method on the model. Now we can get users by status using the below:
User::filterByStatus($status)->get();
Here is the controller code example with local scope now:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class Usercontroller extends Controller
{
public function index()
{
$status = 2;
$users = User::filterByStatus($status)->get();
return view('users', compact('users'));
}
}
I hope that you picked up a few new things about scopes in Laravel. Please feel free to leave a comment if you have any questions or want me to write about another Laravel-related topic.