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

Hey,

I have two 3 models all of them work fine and each one links to the one above.

Company
Distributor -> foreign key to company
Reseller - > foreign key to distributor

Reseller model contains

public function distributor() {
    return $this->belongsTo('App\Distributor');
}

In Artisan I can do
namespace App;
$reseller = new Reseller;
$reseller = $reseller->first();

$reseller->distributor // works fine, gives me the distributor
$reseller->distributor->company // works fine gives me the company

I'm trying to create a shortcut to $reseller->distributor->company inside the Reseller model but I am unsure on how to do that.

Im trying to accomplish $reseller->company

Inside Reseller.php model I tried something like;

public function company() {
    return $this->distributor()->company();
}

But this obviously fails, how can I make the correct relation?

Last updated 3 years ago.
0

I'm not seeing why this shouldn't be working, though it's not one of Laravels magic functions, so you have to add () or use getCompanyAttribute() – but that I would definitely not do that.

$reseller->company();
public function company()
{
    return $this->distributor->company;
}

A tip: Since you talk about "shortcuts", you can also write

return $this->belongsTo(Distributor::class); 

:-)

0
Solution

Thanks for your reply,

It worked with the following! This was needed so that I return a proper eloquent class and not just ab object. Please note how the last ->company() has the () while distributor does not.

public function company() {
    return $this->distributor->company();
}
Last updated 9 years ago.
0

barhom said:

Thanks for your reply,

It worked with the following! This was needed so that I return a proper eloquent class and not just ab object. Please note how the last ->company() has the () while distributor does not.

public function company() { return $this->distributor->company(); }

Thanks. Yes it can sometimes be confusing to remember parentheses or not.

0

Sign in to participate in this thread!

PHPverse

Your banner here too?

barhom barhom Joined 8 Feb 2016

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.