laravel 5.3 - 在刀片模板中显示mysql文本字段的json数据

时间:2016-10-04 13:44:38

标签: php json notifications blade laravel-5.3

我在mysql text字段中有这些数据:

{"message":"New comment from pp on one of your photos.","action":"\/photos\/9372"}

使用此功能(laravel通知)将其写入数据库:

public function toArray($notifiable)
{
    return [
        'message' => 'New comment from '.Auth::user()->username.' on one of your photos.',
        'action' => '/photos/'.$this->comment->photo_id
    ];
}

documentation说:

"The returned array will be encoded as JSON and stored in the data column of your notifications table."

然后我获取这样的数据:

$notifications = Auth::user()->notifications()->paginate(30);

return view('home.index')->with('notifications',$notifications);

如何在刀片视图中显示此json array(?)的内容?我可以var_dump()但不能显示。它总是undefinded index或其他错误。

@forelse($notifications as $n)
    @php
        $data = $n->data;
    @endphp
    {!! var_dump($data) !!}
@empty
    nothing
@endforelse

修改

当我尝试json_decode数据时,它告诉我,它是一个数组:

{!! var_dump(json_decode($data)) !!}

json_decode() expects parameter 1 to be string, array given

print_r()说同样的话:

{!! print_r($data) !!}

Array ( [message] => New comment from pp on one of your photos. [action] => /photos/9372 ) 1 

var_dump()说它是一个数组:

{!! var_dump($data) !!}

array(2) { ["message"]=> string(42) "New comment from pp on one of your photos." ["action"]=> string(12) "/photos/9372" } 

但是当我想显示某个值时,它不起作用:

{!! $data["message"] !!}

Undefined index: message

1 个答案:

答案 0 :(得分:0)

当您尝试访问数组的消息部分时,请确保循环遍历通知数组:

@foreach ($notifications as $notification)
    {{ $notification->data['message'] }}
@endforeach