DEV Community

Morcos Gad
Morcos Gad

Posted on

3 2

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay