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

Dyasis's avatar

Joining tables

Hi all,

I am new to Eloquent, so bare with me please.

Let's say I have 2 tables: users, providers (so in normal php without a framework I would simply join those to tables on users.id and providers.user_id) but from watching Jeffery, I do not have a users_id column in my providers table.

(According to Jeffery I did make a providers_users table which stores the providers.id and users.id, which I think would be the best way to handle this, I just am lost on how to get those and all the other data from the providers table.)

Users belong to many providers Bob can be assigned to 20 providers.

Jane can be assigned to 3 providers

On their page I want to show only the providers of that logged in user. So Bob logs in, he should only see his 20 providers.

In my User model, I have:

public function providers()
    {
        return $this->belongsToMany('App\Providers');
    }
My Controller method has:
        $providers = ... 
        return view('providers.index', compact('providers'));

How to I call that in my controller ?

0 likes
4 replies
RoboRobok's avatar
Level 7

I think what you are looking for is:

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

If you call it in a property-like way, you get a collection of all relations. You can also call it with some query modifications, like this:

$providers = Auth::user()->providers()->whereSomething('foo')->get();
Dyasis's avatar

hmmm, I'm getting "Trying to get property of non-object" so I'm guess it's not returning anything..

RoboRobok's avatar

Did you import Auth namespace or escaped it as \Auth?

If there is nobody logged in, it will return null.

Dyasis's avatar

ok, I put my dunce hat on... I forgot I did not log back in .... :/

Thank you for your help, it works!

Please or to participate in this conversation.