Courses

Laravel 12 Eloquent: Expert Level

Local and Global Scopes for Repeating Conditions

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Implementing local and global scopes
- Creating dynamic scope parameters
- Managing scope application and removal
- Understanding scope best practices

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

Now, let's talk about repeating queries in Eloquent. For example, you have a where() condition, and you want to repeat the same condition in other parts of your application and other Controllers, in other classes, and so on.

$users = User::whereNotNull('email_verified_at')->get();
 
foreach ($users as $user) {
dump($user->id . ': ' . $user->name);
}

You may want to extract that condition into some function, which you would be able to reference in a shorter way. For that, you can use scopes.


Local Scope

You can define that where() condition and put that in a Model in a function with the prefix scope and then scope name.

For example, we can call it scopeVerified(). The parameter is the Eloquent builder, and you provide the where statement in the function.

app/Models/User.php:

use Illuminate\Database\Eloquent\Builder;
 
class User extends Authenticatable
{
// ...
 
public function scopeVerified(Builder $query): void
{
$query->whereNotNull('email_verified_at');
}
}

Since Laravel 12, there's another new syntax: instead of prefixing the method name like scopeXXXXX(), you can just add the PHP attribute on top and change the method from public to protected:

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Attributes\Scope;
 
// ...
 
class User extends Authenticatable
{
// ...
 
#[Scope]
protected function verified(Builder $query): void
{
$query->whereNotNull('email_verified_at');
}
}

To use this scope, instead of the where() condition, we call the...

The full lesson is only for Premium Members.
Want to access all 38 video+text lessons of this course? (1 h 34 min)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord