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.
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();
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community