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

时间:2018-06-25 11:22:40

标签: laravel-5.4

我正试图回显学校里用户的名字。

在学校餐桌上

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

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

对于示范学校

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

all.blade.php

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

我收到此错误

  

试图获取非对象的属性

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

也许我错了

1 个答案:

答案 0 :(得分:1)

试试这个:

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

    // ...
}

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

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