packy
7 months ago
153
11
Eloquent

Scope filter relationship and where clause

Posted 7 months ago by packy

So I am doing a scope filter on a model Account. An account has many users. I am trying to get all the accounts that user has and then filter down by the name. Basically its a live search a user can do within their accounts page.

This works fine to get all the accounts a user has:

 protected function all($username)
    {
        $user = Auth::user();
        return $this->builder->whereHas('users', function ($query) use ($user) {
            $query->where('user_id', $user->id);
        })->get();
    }

This searches all accounts by name fine (but a users should only be able to search their accounts, not all accounts)

protected function name($name)
    {
        

        return $this->builder->where('name', 'LIKE', "% $name% ")
            ->take(5)
            ->get();
    }

What I tried that doesnt work:

protected function name($name)
    {
        $user = Auth::user();

        return $this->builder->whereHas('users', function ($query) use ($user) {
            $query->where('user_id', $user->id);
        })
            ->where('name', 'LIKE', "% $name% ")
            ->take(5)
            ->get();
    }

Please sign in or create an account to participate in this conversation.