dongzun9958 2019-02-05 20:24
浏览 322
已采纳

获取Collection内的Object值

I use DataTables as Service from Yajra in my Laravel application.

I have a collection like this :

Collection {#1178
    #items: array:2 [
    0 => array:7 [
      "email" => "user1@example.com"
      "id" => 6
      "emailBlacklisted" => false
      "smsBlacklisted" => false
      "modifiedAt" => "2019-02-05T17:20:17.723+01:00"
      "listIds" => array:2 [
        0 => 2
        1 => 3
      ]
      "attributes" => {#1139
        +"NAME": "Doe"
        +"FIRSTNAME": "John"
      }
    ]
    1 => array:7 [
      "email" => "user2@example.com"
      "id" => 1
      "emailBlacklisted" => false
      "smsBlacklisted" => false
      "modifiedAt" => "2019-02-05T21:12:04.094+01:00"
      "listIds" => array:1 [
        0 => 2
      ]
      "attributes" => {#1143}
    ]
  ]
}

In my blade view I show email value with {{ $email }} -> Simple

I think this is a very easy problem for you ...

But I can't display the value of attributes key. (I want to show the NAME : Doe). -> attributes is an object inside my collection.

Thank you for helping me unlock...

  • 写回答

3条回答 默认 最新

  • dongxili9934 2019-02-06 03:45
    关注

    If I'm understanding correctly, you want to be able to display the key and the value of the attributes.

    If you are utilizing blade, you could try an expanded foreach loop:

    @foreach($attributes as $key => $value)
        {{ $key }}: {{ $value }}
    @endforeach
    

    This assumes that you already have access to the attributes on each individual model, such as $item->email or in this case $item->attributes. If you need to, you can do @foreach($item->attributes as $key => $value) to start it off.


    If you are only looking to display a specific value, use the null-coalesce operator ??.

    $item->attributes['NAME'] ?? ''
    

    You could use this in your logic elsewhere with any expression that might be null:

    // the fallback does not have to be a string
    $person = Person::find($id) ?? Person::first();
    
    // it can be chained
    $value = $parameter ?? $localDefault ?? $globalDefault;
    

    If the NAME is not found, it will fall back to what comes after the ??, which is an empty string in the example above. This is a nice trick to avoid any errors if the attribute doesn't exist. It is doing the same thing as a ternary checking if it is null:

    ($item->attributes['NAME'] !== null) ? $item->attributes['NAME'] : '';
    

    That is obviously messy, so the null-coalesce operator comes in handy!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示