【问题标题】:Trying to get property of non-object in laravel 5.4试图在 laravel 5.4 中获取非对象的属性
【发布时间】:2018-12-03 23:03:34
【问题描述】:

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

学校餐桌

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

也许我错了

【问题讨论】:

    标签: laravel-5.4


    【解决方案1】:

    试试这个:

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

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

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

    【讨论】:

    • 哦,我在三周内就参与了。谢谢
    猜你喜欢
    • 2018-01-01
    • 2018-04-05
    • 2017-11-05
    • 2017-12-27
    • 1970-01-01
    • 2018-08-27
    • 2017-09-24
    • 1970-01-01
    • 2015-08-19
    相关资源
    最近更新 更多