【问题标题】:I'm using Laravel with Laratrust, How to print a role that's attached to an account? [duplicate]我将 Laravel 与 Laratrust 一起使用,如何打印附加到帐户的角色? [复制]
【发布时间】:2021-03-24 17:36:02
【问题描述】:

在我的主页中,我可以使用以下方式打印登录帐户的名称和电子邮件:
{{ Auth::user()->name }}
{{ Auth::user()->email }}

但是当我想使用这个打印附加到帐户的角色时:
{{ Auth::user()->roles }}

它会打印表中所有数据的键和值的集合,如下所示:
[{"id":3,"name":"mahasiswa","display_name":"Mahasiswa","description":"Mahasiswa","created_at":"2021-03-22T13:09:14.000000Z","updated_at":"2021-03-22T13:09:14.000000Z","pivot":{"user_id":4,"role_id":3,"user_type":"App\\Models\\User"}}]

我只想提取名称或显示名称。

所以,我使用的是{{ Auth::user()->roles->where('name')->first() }},但它仍然显示相同的集合,但没有“[]”括号。

【问题讨论】:

  • 你可以试试这个{{ Auth::user()->roles->get(['name']) }}
  • 是的,确实如此,我只需要在角色->first() 之后指定键名,所以角色->first()->display_name

标签: laravel eloquent laratrust


【解决方案1】:

您应该先获取第一条记录,然后再获取字段。

{{ Auth::user()->roles->first()->get('name') }}

这是来自文档的参考

https://laravel.com/docs/8.x/collections#method-get

【讨论】:

  • 这会打印所有具有“名称”列的角色(我有 3 个角色,并且该代码会打印所有 3 个角色,这不会打印附加到已登录帐户的角色。跨度>
【解决方案2】:

感谢大家的回答!我很感激。

但我刚刚在这里找到答案https://stackoverflow.com/a/39357511/15471776

因此,我将代码更改为{{ Auth::user()->roles->first()->display_name }},它完美地显示了附加到我登录帐户的角色名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 2021-08-10
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    相关资源
    最近更新 更多