我将订单数据保存到notifications
表作为我的通知using laravel Notification
,我在返回数据时遇到问题。
这是我的通知方法:App\Notifications\OrderSubmited.php
public function toArray($notifiable)
{
return [
'order_id' => $this->order->id,
'title' => $this->order->title,
'buyer' => $this->order->user_id,
'status' => $this->order->orderstatus_id,
];
}
获取数据的方法:
View::composer('admin.dashboard', function ($view) {
$notifications = DB::table('notifications')->orderby('id', 'desc')
->latest()
->take(5)
->get();
$notifs = $notifications;
$view->with('notifs', $notifs);
});
这是我的刀片代码:
@foreach($notifs as $notif)
{{dd($notif)}}
@foreach($notif->data as $data)
{{$data['order_id']}} <br>
@endforeach
@endforeach
这是我的{{dd($notif)}}
输出:
{#721 ▼
+"id": "46546547464415474884"
+"type": "App\Notifications\OrderSubmited"
+"notifiable_id": 2
+"notifiable_type": "App\Order"
+"data": "{"order_id":2,"title":"tsdfg", "user_id":"1", "orderstatus_id":"11"}"
+"read_at": null
+"created_at": "2018-01-18 00:00:00"
+"updated_at": "2018-01-18 00:00:00"
}
data
列。如果我删除dd
,我会收到此错误:
为foreach()提供的参数无效
在这一行:
@foreach($notif->data as $data)
有什么想法吗?
答案 0 :(得分:1)
每个通知都是一个对象,其中包含一个名为data
的数组,其中包含您在创建通知时从toArray
方法返回的值。您通常会遍历通知并访问其数据,如下所示:
@foreach ($notifications as $notification)
{{ $notification->data['order_id'] }}
@endforeach
Laravel将data
属性(以JSON格式存储在数据库中)转换为数组。
但是,因为您是在不使用内置方法的情况下自己从数据库中检索通知的,所以您需要自己将这些数据转换为JSON数组,如下所示:
View::composer('admin.dashboard', function ($view) {
$notifications = DB::table('notifications')->orderby('id', 'desc')
->latest()
->take(5)
->get();
$view->with('notifications', $notifications);
});
然后从您的视图中:
@foreach ($notifications as $notification)
@php $data = json_decode($notification->data, true); @endphp
{{ $data['order_id'] }}
@endforeach
关于你的后续问题,如下:
View::composer('admin.dashboard', function ($view) {
$notifications = DB::table('notifications')->orderby('id', 'desc')
->latest()
->take(5)
->get()
->map(function ($item, $key) {
$item->data = json_decode($item->data);
$item->data->user = User::find($item->data->user_id);
return $item;
});
$view->with('notifications', $notifications);
});
然后从您的视图中:
@foreach ($notifications as $notification)
{{ $notification->data->user->name }}
@endforeach