Skip to content
Advertisement

Access nested related objects with where clause in Laravel using Eloquent

I’m trying to get a list of tasks that are associated with a specific client, but there is no direct relation between a task and a client. I also need to filter those tasks based on task status and project status.

Here are my models:

JavaScript

In my controller, I have direct access to Client $client from the request.

The goal is to return a list of tasks which have a status of ‘open’ and which are children of projects owned by the client.

Basically, I want to write something like this:

JavaScript

And I want to get back what I’d get from this query:

JavaScript

I’ve been able to solve it using Laravel’s Query Builder, but I want a solution that uses Eloquent’s ORM directly.

JavaScript

This seems to be a variation on a common question, but I’ve been unable to solve it with the other answers posted here.

Related questions:

laravel orm : where condition on table -> related table -> related table

Laravel nested relationships

Advertisement

Answer

What you are looking for is whereHas. It lets you query “results based on the existence of a relationship”.

You could try something like:

JavaScript

hasManyThrough also applies on this structure:

JavaScript

However not entirely sure if this would work.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement