问题
I'm trying to echo out the name of the user in my school.
For school table
Schema::create('schools', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('school_name');
$table->string('status');
$table->string('gender');
$table->string('notes');
$table->string('member_name');
$table->string('type');
$table->string('file_number');
$table->string('phone');
$table->string('address');
});
For SchoolController
public function show(School $school)
{
$province_names = Province::all();
$city_names = City::all();
$center_names = City::all();
return view('school.all', compact('school','city_names', 'province_names', 'center_names'));
}
For model School
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
all.blade.php
{{ $school->user->firstـname }}
I get this error
Trying to get property of non-object
But I writted {{ dd($school->user) }}
display null
.
Maybe I'm wrong
回答1:
Try this:
public function show($id) {
$school = School::with('user')->where('id', $id)->first();
// ...
}
Or auto-load relation on your model:
class School extends Model {
protected $with = ['user'];
}
来源:https://stackoverflow.com/questions/51022315/trying-to-get-property-of-non-object-in-laravel-5-4