试图在 laravel 5.4 中获取 属性 的非对象

Trying to get property of non-object in laravel 5.4

我正在尝试呼出学校用户的姓名。

学校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');
});

对于学校控制器

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'));
}

模范学校

public function user()
{
    return $this->belongsTo(User::class, 'user_id');
}

all.blade.php

{{ $school->user->firstـname }}

我收到这个错误

Trying to get property of non-object

但是我写了{{ dd($school->user) }}显示null

也许我错了

试试这个:

public function show($id) {
    $school = School::with('user')->where('id', $id)->first();

    // ...
}

或在您的模型上自动加载关系:

class School extends Model {
    protected $with = ['user'];
}