Skip to content
Advertisement

Laravel get school users

I am making a project that will have schools that are already seeded into the database, one user has one school.

User table has school_id

I made this relationship:

User.php

public function school(){
    return $this->belongsTo('AppModelsSchool');
}

School.php

 public function user()
{
    return $this->hasMany('AppModelsUser', 'school_id');
}

When i do

$school = School::where('id', 1)->first();

dd($school);

I get every field from the school model but the users aren’t there,how do i make that the users appear there too without having to do?

dd($school->user)

Advertisement

Answer

You should use the Eloquent feature called Eager Loading

So, to eager load all the users, you should do:

School::with('user')->get();

Alternatively, if you are willing to automatically load the user without having to specify with(‘user’) every time, you can set the $with property in your School model like this:

protected $with = [‘user’];

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement