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...