how about
Auth::user()->projects()->with('items')->get()->map(function ($project) {
return $project->items;
})->flatten();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have 3 tables. Users, Projects, Items. There's also a Pivot Table Project_User for the many-to-many relationship between projects and users.
So I can get projects assigned under the logged in user like:
Auth::user()->projects()->get().
This is working fine.
Items belongsTo one project.
Now I'm not sure how to build the relationship so that I can retrieve the items similar to how I get the projects.
Something like: Auth::user()->items()->get().
Option 1: I can get all the projects associated with the user first, then iterate everyone to get the items. I don't like this cause I think it should be possible to do it in one step?
Options 2: Somehow I can build a relationship or query in User.php to get access directly to items? This is the part I'm not sure of.
So I realise mine is a typical hasManyThrough pivot table problem.
Doesn't seem like there's a good solution around.
because we are querying the projects, not the item :)
so we should do like this
Item::whereHas('project.users', function ($query) {
$query->where('id', auth()->id());
})->orderBy('updated_at', 'desc')->paginate($limit)
*updated
Please or to participate in this conversation.