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

ronnyandre's avatar

Relationships through a polymorphic table

I have three models: User, Company and Project.

A Company has several Projects, and a User has access to several Companies. For that I have the following tables:

**Users**
id
name
email
...

**Companies**
id
name
...

**Projects**
id
name
company_id
user_id (e.g. the user that created the project)
...

**Company_User**
id
company_id
user_id

I want to fetch all projects for a specific user, based on which company he has access to. Am I wrong to thing that this would be correct:

$projects = Auth::user()->projects;

And have a method on the User model, or would it be more correct like this:

$projects = Auth::user()->companies()->projects;

I think the first one seems more correct, but I'm not sure how to do the method on the User model to fetch all projects through Company_User / Company table.

0 likes
1 reply
bobbybouwmann's avatar

Well you need to use multiple relations here to do that.

So for example this would get all projects of the user

$user = Auth::user();
$user->load('companies.projects');

// Now you can access all the projects like
foreach ($user->companies as $company) {
    $company->projects;
}

// You can for example use the collection methods to merge them to one collection
https://laravel.com/docs/5.6/collections#method-flatten

Another option is to do two queries to fetch everything at once

$companies = Auth::user()->companies;
$projects = Project::whereIn('company_id', $companies->pluck('id'))->get();

Let me know if this works for you ;)

Please or to participate in this conversation.