如何修复 laravel 8 中的“尝试获取非对象的属性‘标题’”错误

问题描述 投票:0回答:2

背景: 我安装了新的 Laravel 版本 8.49.2,并从(旧版 Laravel v5.8 项目)中移动了我的应用程序逻辑(控制器、路由、视图、中间件、模型、自定义配置),到目前为止,一切都按预期运行良好。

但是当我访问刀片中的关系属性时,出现以下错误:

Trying to get property 'title' of non-object (View: /Path/to/resources/views/users.blade.php)

刀片:

@foreach($users as $user)
<p> {{ $user->roles->title }} </p>
@endforeach

这个

<p> {{ $user['roles']['title'] }} </p>
or
<p> {{ $user->roles['title'] }} </p>

还给出错误

Trying to access array offset on value of type null

控制器:

$users = User::with(['roles'])->get();
return view('users', compact('users'));

用户型号:

public function roles()
{
    return $this->belongsTo(Role::class, 'levelId'); 
}

榜样:

    public function users()
{
    return $this->hasMany(User::class, 'levelId');
}

当我死亡并转储时

dd($user->roles->title)
我得到了价值
"Admin"
但只是像这样
{{ $user->roles->title }}
那样回显就会给出错误。

注意: 当我将 PHP 版本更改为 7.3 时,不会出现错误。但在 PHP 7.4.20 或 7.4.21 中会出现此错误。但我需要 PHP 7.4.* 有谁知道我该如何解决这个问题?

php laravel laravel-5 eloquent laravel-8
2个回答
3
投票

看起来有些用户没有角色。所以最好检查是否为空。当您

dd($user->roles->title)
时,它仅检查第一个用户记录,而不是所有用户。

@foreach($users as $user)
<p> {{ $user->roles->title??null }} </p>
@endforeach

-1
投票

@foreach($users 作为 $user)

{{ $user-roles->title??nul @endforeach

© www.soinside.com 2019 - 2024. All rights reserved.