简体   繁体   English

拉拉维尔。 我无法显示关系中的数据

[英]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

$user->roles is a collection of elements, you are trying to get a property on a list of elements. $user->roles是元素的集合,您正在尝试获取元素列表上的属性。

You could use implode for example to display all roles comma seperated.例如,您可以使用implode来显示以逗号分隔的所有角色。

{{ $user->roles->implode('name', ', ') }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Laravel。 我无法从列中读取数据 - Laravel. I can't read the data from the column Laravel。 具有关系的模型中的范围() - Laravel. scope() in models with relation Vs Code 将代码标记为不是 Laravel 中的错误的错误。 我怎样才能阻止它显示这些错误/任何错误? - Vs Code is marking codes as errors that aren't errors in Laravel. How can I stop it from showing those errors/any errors? Laravel。 从数据透视表获取数据 - Laravel. Get data from pivot table 我的节目 function 在 Laravel 中不起作用。 URL 显示特定的 id,但在页面数据不会来 - My show function is not working in Laravel. URL shows the particular id, but in the page data won't come 无法从Laravel 5.5中的关系表中获取数据 - Can't fetch data from relation table in laravel 5.5 我的数据库连接在 laravel 中不起作用。 我可以通过 CLI 连接,但不能在 webapp 中连接 - My database connection doesn't work in laravel. I can connect through CLI but not in the webapp Laravel. Eager Load 不工作但关系存在 - Laravel. Eager Load not working but relation exist Laravel。 从 ElasticSearch 获取 model 数据的最佳做法是什么? - Laravel. What is the best practice to get model data from ElasticSearch? Controller 在 laravel 中不存在。我该如何解决这个问题? - Controller doesnt exists in laravel. how can i solve this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM