如何在Blade视图中显示JSON数组?

时间:2017-01-07 16:11:09

标签: json laravel laravel-5

My db table structure

我使用视图编辑器从此表中获取数据并将其发送回我的视图

class NavComposer
{

 public function compose(View $view)
    {
        if (Auth::check()) {
            $view->with('unread_notifications', DB::table('notifications')->where([
                                            ['read_at', '=', NULL],
                                            ['notifiable_id', '=', Auth::user()->id],
                                            ])->get());
        }
    }
}

我的观点:

@foreach($unread_notifications as $notification)
{{ $notification->data }}
@endforeach

我得到的是什么:

{"id":79,"sender":"Diana","receiver":"Alex","subject":"Subject","body":"Lorem ipsum"}

我想要展示的内容:

ID: 79
Subject: Subject
Body: Lorem Ipsum

我提前道歉,如果这是非常简单的东西,我对JSON不太了解

2 个答案:

答案 0 :(得分:1)

您需要解码JSON。您可以手动执行此操作:

@foreach($unread_notifications as $notification)
    <?php $notificationData = json_decode($notification->data, true); ?>
    {{ $notificationData['sender'] }}
@endforeach

或者你可以create accessor因此Laravel可以自动将JSON转换为数组:

public function getDataAttribute($value)
{
    return json_decode($value, true);
}

答案 1 :(得分:0)

@foreach($unread_notifications as $notification)
   @foreach(json_decode($notification->data, true) as $d)
      <div>ID: {{ $d['id'] }}</div>
      <div>Subject: {{ $d['subject'] }}</div>
      <div>Body: {{ $d['body'] }}</div>
   @endforeach
@endforeach