Eager load Laravel Eloquent related model

10,631

Try:

public function allCompanies() {
    $companies = $this->companies()->active()->with('industry')->get();
    return $companies;
}

The with() and load() functions are referencing functions within the model not the model itself ie:

class Company extends Eloquent {

    public function industry()
    {
        return $this->belongsTo('Industry');
    }
}
class Industry extends Eloquent {

        public function companies()
        {
            return $this->hasMany('Company');
        }
}

Please reference http://laravel.com/docs/eloquent#eager-loading

Share:
10,631
ArthurGuy
Author by

ArthurGuy

Updated on June 30, 2022

Comments

  • ArthurGuy
    ArthurGuy almost 2 years

    I am trying to get eager loading working when fetching related models.

    public function allCompanies() {
        $companies = $this->companies()->active()->get();
        $companies->load('Industry');
        return $companies;
    }
    

    I have this function on the model Industry and I believe this should fetch the companies which are within the current industry, it should also fetch the related industry for the companies (this will be the current record)

    This doesn't seem to work as when I iterate over the companies it re-fetches the Industry for each one.

    Am I doing something wrong with the $companies->load('Industry'); line?

    Thanks