【问题标题】:laravel 5.3 - display json data from mysql text field in blade templatelaravel 5.3 - 在刀片模板中显示来自 mysql 文本字段的 json 数据
【发布时间】:2023-03-06 06:36:01
【问题描述】:

我在 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

【问题讨论】:

    标签: php json notifications blade laravel-5.3


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 2014-09-14
      • 2014-11-07
      • 2020-07-10
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      相关资源
      最近更新 更多