Php 从laravel 5.5中的数组列中获取数据
我使用laravel notification将订单数据保存到Php 从laravel 5.5中的数组列中获取数据,php,laravel,laravel-blade,Php,Laravel,Laravel Blade,我使用laravel notification将订单数据保存到通知表中作为我的通知,并且我在返回数据时遇到问题 以下是我的通知方法:App\Notifications\OrderSubmited.php public function toArray($notifiable) { return [ 'order_id' => $this->order->id, 'title' => $this->
通知
表中作为我的通知,并且我在返回数据时遇到问题
以下是我的通知方法: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
- 正如您所看到的,我尝试返回的数据存储在
data
列中
如果我删除我的dd
,我将得到以下错误:
为foreach()提供的参数无效
在这一行:
@foreach($notif->data as $data)
有什么想法吗?每个通知都是一个对象,其中包含一个名为data
的数组,其中包含创建通知时从toArray
方法返回的值。您通常会遍历通知并访问其数据,如下所示:
@foreach ($notifications as $notification)
{{ $notification->data['order_id'] }}
@endforeach
Laravel将数据
属性(作为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
@foreach ($notifications as $notification)
{{ $notification->data->user->name }}
@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)
@php $data = json_decode($notification->data, true); @endphp
{{ $data['order_id'] }}
@endforeach
@foreach ($notifications as $notification)
{{ $notification->data->user->name }}
@endforeach
非法字符串偏移量'order\u id'
@maforti很抱歉,我太早按了enter键,现在检查我的答案:-)仍然说非法字符串偏移量'order\u id'
我必须在notificationb模型中添加任何内容吗?但是,当您使用laravel通知时
将不会有任何模型(无需这样做!),但如果有必要,我会为其制作吗?我的意思是制作一些类似于的演员
等。对不起,我的答案有一个输入错误,请重试:应该是{$data['order\u id']}
而不是{$notification->data['order\u id']}
是的,只需在映射中添加一个额外的赋值,例如:$item->data->orderstatus=orderstatus::find($item->data->orderstatus\u id)代码>和$item->data->order=order::find($item->data->order\u id)代码>然后您可以作为{{$notification->data->orderstatus->property}}
和{{$notification->data->order->property}}