Video Version of the Lesson
[Only for premium members]
[Only for premium members]
[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.
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...