Trying to get property of non-object in laravel 5.4

天涯浪子 提交于 2019-12-11 16:07:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!