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(''))->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', '');
Enter fullscreen mode Exit fullscreen mode

we want to call multiple scopes on a query

    ->tap(new MatchingEmail(''))
    ->tap(new ActiveUser())

    new MatchingEmail(''),
    new ActiveUser()
Enter fullscreen mode Exit fullscreen mode

I hope you will visit the source to go deeper and benefit from this article in your future projects.

Top comments (0)