简体   繁体   中英

How to get second value from array in Laravel

I seem to have hit many snags trying to get to this point so I'm quite surprised I've even got this far.

I'm trying to get a role name (from roles table) through the users table

I currently have:

{{ Auth::user()->role }}

Which gives me:

Role : 1 [{"id":1,"name":"Float","created_at":"2018-03-19 00:00:00","updated_at":"2018-03-19 00:00:00","pivot":{"user_id":1,"role_id":1}}]

But once I try:

{{ Auth::user()->role->name }}

I get:

Property [name] does not exist on this collection instance. 

Surely that should work? the name field is clearly there in the array.

What am I missing to make this work?

As you say, the name property exists in the array . The object exists within an array, and you need to access the array first, specifying which index of role you wish to access:

{{ Auth::user()->role[0]->name }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM