Search code examples
constructoreloquentbelongs-to

Illuminate/Eloquent: how to use belongsTo in constructor


i would like to provide data from the "foreign key table" in the current model.

I am currently achieving this by a function (getBrand).

But now I would like to have this accessable as a property. So I added a property ($brand) and wanted to fill it by calling the function (getBrand) in the constructor of the model.

class Car extends Eloquent {
  public $brand;

  public function __construct() {
    parent::__construct();
    $this->brand = getBrand();
  }

  public function getBrand() {
    return $this->belongsTo('App\Brand', 'FK_BrandId')->first()->Brandname;
  }
}

But this creates an error during the execution of the constructor:

Trying to get property of non-object

Any ideas how to solve this? Thanks!


Solution

  • You could change your getBrand function a little to the following to define the relationship between a Car and a Brand:

     public function brand() {
        return $this->belongsTo('App\Brand', 'FK_BrandId');
     }
    

    The brand model can then be accessed from an instance of Car with, e.g. $car->brand. To access the brand name you can then use $car->brand->Brandname.

    If you'd like to access the brand name directly, you could define an "accessor" on the Car model like this:

    public function getBrandNameAttribute()
    {
        return $this->brand->BrandName;
    }
    

    You would then be able to access the brand name with $car->brand_name.