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

theUnforgiven's avatar

Pivot Data on Query

I have a basic query to get all users:

return User::orderBy('name')
                    ->where('id', '!=', auth()->user()->id)
                    ->get();

But I also have a company_user pivot table, which within the above query I need to pass this in, allowing the query to show the 4 rows in the pivot table. This is then saying there are 4 users associated with this company.

This is my pivot table.

So my question is based on my code above, how can I get the pivot to work thus showing 4 users, whereas currently it shows 20 users, all the users on my test database which I don't want.

0 likes
10 replies
nsvetozarevic's avatar

You didn't specify which users do you want. The correct way would be to set the appropriate relations, and then if you want company users, do something like this: $company->users and you'll get the users you need.

theUnforgiven's avatar

User Model

public function company()
{
        return $this->belongsTo(Company::class);
}

Company Model

 public function users()
{
        return $this->hasMany(User::class, 'company_user', 'user_id', 'id');
}

Then within my controller I call

return Company::with('users')->where('owner_id', '=', user()->companies()->first()->id)->orderBy('name')->get();

Should be get all users associated with the authenticated user's company id like user()->companies()->first()->id shows

Vilfago's avatar
$auth_user = auth()->user();
return User::orderBy('name')
                    ->where('id', '!=', $auth_user->id)
                    ->whereHas('company', function ($query) use($auth_user) {
    $query->where('id', '<>', $auth_user->company->id);
                    ->get();

Something like that should do the job

theUnforgiven's avatar

I get Trying to get property of non-object on line 19 which responds to $query->where('id', '<>', $auth_user->company->id);

Based on:

$auth_user = user(); //auth()->user();
    return User::orderBy('name')
                    ->where('id', '!=', $auth_user->id)
                    ->whereHas('company', function ($query) use($auth_user) {
                          $query->where('id', '<>', $auth_user->company->id);
                    })
                    ->get();
Vilfago's avatar

Because your relation is wrong

public function company()
{
        return $this->belongsToMany(Company::class);
}

As you use a pivot table... but if the user have many companies, which users you want to get ?

nsvetozarevic's avatar

The relationship name should be companies hence your user has multiple companies, not one. So you will have o specify the id of the company you're trying to get users from.

1 like

Please or to participate in this conversation.