[英]How can I fix this error “Trying to get property 'title' of non-object” in laravel 8
Background: I installed a new Laravel version 8.49.2, and moved my app logic (controllers, routes, views, middlewares, models, custom configs) from (a legacy Laravel v5.8 project), Everything works well as expected so far.背景:我安装了一个新的 Laravel 8.49.2 版本,并将我的应用程序逻辑(控制器、路由、视图、中间件、模型、自定义配置)从(一个遗留的 Laravel v5.8 项目)中移出,到目前为止一切都按预期运行。
But when I access a relationship attribute in blade I get the following error: Trying to get property 'title' of non-object (View: /Path/to/resources/views/users.blade.php)
但是当我访问刀片中的关系属性时,我收到以下错误: Trying to get property 'title' of non-object (View: /Path/to/resources/views/users.blade.php)
Blade:刀:
@foreach($users as $user)
<p> {{ $user->roles->title }} </p>
@endforeach
This这
<p> {{ $user['roles']['title'] }} </p>
or
<p> {{ $user->roles['title'] }} </p>
Also gives the error Trying to access array offset on value of type null
还给出了错误Trying to access array offset on value of type null
The Controller:控制器:
$users = User::with(['roles'])->get();
return view('users', compact('users'));
User Model:用户模型:
public function roles()
{
return $this->belongsTo(Role::class, 'levelId');
}
Role Model:榜样:
public function users()
{
return $this->hasMany(User::class, 'levelId');
}
When I die and dump dd($user->roles->title)
I get the value "Admin"
But just echoing it like so {{ $user->roles->title }}
gives the error.当我死掉并转储dd($user->roles->title)
我得到了值"Admin"
但只是像这样回应它{{ $user->roles->title }}
给出了错误。
NOTE: When I change my PHP version to 7.3, this does not give an error.注意:当我将 PHP 版本更改为 7.3 时,不会出现错误。 But in PHP 7.4.20 or 7.4.21 this error occurs.但在 PHP 7.4.20 或 7.4.21 中会发生此错误。 But I need PHP 7.4.* Does anyone know how I can solve this?但我需要 PHP 7.4.* 有谁知道我如何解决这个问题?
Look like some users doesn't have role .So better check for null.When you dd($user->roles->title)
it only check for first user record not for all users.看起来有些用户没有角色。所以最好检查空值。当你dd($user->roles->title)
它只检查第一个用户记录而不是所有用户。
@foreach($users as $user)
<p> {{ $user->roles->title??null }} </p>
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.