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