试图在laravel 5.4中获取非对象的属性 [英] Trying to get property of non-object in laravel 5.4

查看:96
本文介绍了试图在laravel 5.4中获取非对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to echo out the name of the user in my school.

在学校餐桌上

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

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

对于示范学校

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

all.blade.php

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();

    // ...
}

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

Or auto-load relation on your model:

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

这篇关于试图在laravel 5.4中获取非对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆