Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

socieboy's avatar

Need help with query

I have a model Project, The model has the relationship belongsTo User. (The creator of the project) But also has another relationship hasMany User. (The creator can invite other users to the project)

So I want to make a query to return all projects that the auth user create and also the ones that the auth has been invited.

public function scopeSearch($query, $search)
    {
        $query->where('user_id', auth()->id());
    // $query->{ also the ones that auth()->id() has been invited}
    }

I want to be able to do this:

return Project::search(request('search'))->paginate();
0 likes
1 reply
arukomp's avatar
arukomp
Best Answer
Level 10
    public function scopeSearch($query, $search)
    {
        $query->where('user_id', auth()->id())
            ->orWhere(function ($query) {
                $query->whereHas('invitedUsers', function ($query) {
                    $query->where('id', auth()->id());
                });
            });
    }

Please or to participate in this conversation.