Courses

Laravel 11 Eloquent: Expert Level

Local and Global Scopes for Repeating Conditions

Summary of this lesson:
- Implementing local and global scopes
- Creating dynamic scope parameters
- Managing scope application and removal
- Understanding scope best practices

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): Builder
{
return $query->whereNotNull('email_verified_at');
}
}

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

The full lesson is only for Premium Members.
Want to access all 28 lessons of this course? (71 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord