Merklin's avatar

Filter collection using custom table

Hello all.

I am struggling with a query I want to build. I have 2 models, users and projects with ManyToMany relationship.

I am showing the results for projects using this code:

$projects = auth()->user()->projects()->sortable()->paginate(config('PAGINATION_NUM'));
return view('projects.view', compact('projects'));

Now I'd like to add filtering by a client name. The clients are in a separate table named clients and the relationship is BelongsTo (a field client_id in the projects table).

Basically, I want to be able to filter projects by client name.

How can this be done?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Assuming the relation name is client on the Project model; you can use whereHas like this:

$projects = auth()->user()->projects()
    ->whereHas('client', fn($builder) => $builder->where('name', $clientName))
    ->sortable()
    ->paginate(config('PAGINATION_NUM'));
1 like

Please or to participate in this conversation.