Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

Hi.

I am a little confused sometimes when using the relations in Eloquent. Can you help me?

I have in my User.php model

public function organisation() {
    return $this->belongsTo('Organisation');
}

And in my users table I have an organisation_id integer field set up as a foreign key.

When I am trying to access the organisation, I would think these two ways of writing would give the same result:

// Return the id of the users organisation
$id = Auth::user()->organisation->id

and

// Return the id of the users organisation
$id = Auth::user()->organisation()->id

However, only the first one works. In the first example Auth::user()->organisation returns an Organisation object, which is what I would expect, but Auth::user()->organisation() returns an Illuminate\Database\Eloquent\Relations\BelongsTo object which I can't use.

I find this very confusing. Can you help me understand it? Is this the way it's supposed to be?

Regards, Skovmand.

Last updated 3 years ago.
0

when you use () it compounds with Query Builder and lets you continue query operations on the next item... When you do not, it pulls the relationship instead...

Auth::User()->organization->id;

Auth::User()->organization()->where('organization_id', 1)->get();

Last updated 3 years ago.
0

Okay. Thanks!

In this case using the query builder wouldn't make much sense, but if it's a many-to-many or hasmany relationship it would.

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

skovmand skovmand Joined 27 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.