DEV Community

Morcos Gad
Morcos Gad

Posted on

Tappable Query Scopes - Laravel ( tap() )

Today we will learn about using a new function, which is tap() with Query Scopes, and the most important features that it gives us and benefit from it in allow you to create class based scopes that are invokable, and are called using the tap() method in Laravel

class MatchingEmail
{
    public function __construct(
        protected readonly string $email,
    ) {}

    public function __invoke(Builder $query): void
    {
        $query->where('email', $this->email);
    }
}

User::query()->tap(new MatchingEmail('taylor@laravel.com'))->get();
Enter fullscreen mode Exit fullscreen mode

So what we have is an invokable class that acts like a callable that we can simply call to extend the query we are building. So in effect the above example could use the below

User::query()->tap(function (Builder $query) {
    $query->where('email', 'taylor@laravel.com');
})->get();
Enter fullscreen mode Exit fullscreen mode

we want to call multiple scopes on a query

User::query()
    ->tap(new MatchingEmail('taylor@laravel.com'))
    ->tap(new ActiveUser())
    ->get();

User::query()->filter(
    new MatchingEmail('taylor@laravel.com'),
    new ActiveUser()
)->get();
Enter fullscreen mode Exit fullscreen mode

I hope you will visit the source https://www.juststeveking.uk/tappable-query-scopes-in-laravel/ to go deeper and benefit from this article in your future projects.

Top comments (0)