Search code examples
laraveleloquenteloquent-relationshiplaravel-relations

Laravel model with preloaded relation


I have a DB table that stores my job titles so as not to duplicate them, and the Job model has relationships internally, so when I use the Eloquent Model I have to always call or load the JobTitles model over and over again. Is there a way to always use the Job Model with pre-loaded JobTitles inside?

    class Job extends Model
    {
        use Notifiable;

        protected $fillable = [ ... ];

        protected $hidden = [
        'token',
        ];


    
        public function title()
        {
            return $this->belongsTo('App\Models\JobTitle','job_title_id');
        }

        public function people()
        {
            return $this->belongsToMany('App\Models\Person','job_person','job_id','person_id');
        }
        
    }

This is JobTitle model

class JobTitle extends Model
{
    use Notifiable;

    protected $table = "job_titles";

    protected $primaryKey = 'job_title_id';

    protected $fillable = [
        'name',
    ];

    protected $hidden = [
    'token',
    ];


    public function jobs()
    {
        return $this->hasMany('App\Models\Job','job_title_id');
    }

    
}

Now my code inside of the controller looks like this:

 $job = Job::all()->load('title');

It is working fine but when I am calling jobs from people

 $personJobs = Person::find(1)->jobs()->load('title')->get();

gives error, Any ideas how this is done?


Solution

  • To always use the Job Model with pre-loaded JobTitles inside. you can add $with attribute in your job model:

    class Job extends Model
    {
       use Notifiable;
       
       protected $with = ['title'];
    
    }