[英]Laravel. I can't show data from relation
i have strange problem.我有奇怪的问题。 dd(), It shows me that I got to the data, but i cant display single record from table.
dd(),它显示我得到了数据,但我无法显示表中的单个记录。
I want to get to the name of my role but i get this error :我想知道我的角色名称,但出现此错误:
Property [name] does not exist on this collection instance
此集合实例上不存在属性 [名称]
Model - User模型 - 用户
public function roles()
{
return $this->belongsToMany(Role::class);
}
Controller控制器
$users = User::with('roles')->get();
return view('pages.user', compact('users'));
View看法
@foreach($users as $user)
{{$user->id}}
<br>
{{$user->name}}
<br>
{{$user->email}}
<br>
{{$user->roles->name}} //this not working
<br>
<br>
@endforeach
When Im using {{$user->roles}}
I get当我使用
{{$user->roles}}
我得到
{"id":1,"name":"Admin","description":"this is admin","pivot":{"user_id":2,"role_id":1}}]
{"id":1,"name":"Admin","description":"这是管理员","pivot":{"user_id":2,"role_id":1}}]
what Im doing wrong?我做错了什么? Thx for help.
谢谢你的帮助。
$user->roles
return a collection as it's defined as a belongsToMany
relation and you cannot access name
from it. $user->roles
返回一个集合,因为它被定义为belongsToMany
关系并且您不能从中访问name
。
Either you have to iterate through the collection or get the first one.您必须遍历集合或获取第一个集合。
$user->roles->first()->name
or或者
@foreach ($user->roles as $role)
{{ $role->name }}
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.