因此,我从控制器、Routes和app.blade.view中获得了这些代码:控制器:
public function showNotif(){
$dataNotif= Notification::get();
// dd($dataNotif);
return view('/',compact('dataNotif'));
}
路线:
Route::get('/','homeController@showNotif');
在app.blade.view中,我在显示通知的可点击铃声图标中得到了这些代码:
@if(isset($dataNotif))
@foreach($dataNotif as $dn)
<a href="#" class="dropdown-item dropdown-item-unread">
<div class="dropdown-item-desc">
<p>{{$dn->notifikasi}}</p>
</div>
</a>
@endforeach
@else
<a href="#" class="dropdown-item dropdown-item-unread">
<div class="dropdown-item-desc">
<p>No Notifications!</p>
</div>
</a>
@endif
当我试图在app.blade.view中使用foreach方法时,它总是显示";未定义变量";关于$dataNotif错误,但当我第一次使用isset时,没有数据显示,应该是2个通知数据显示在我打开主网站时。。。
那么,我有没有犯过什么概念错误或小错误呢?
谢谢你的回答。。
如果我们不知道您的Notification类是什么样子的,并且上次我检查通知中的数据是通过$notification->data['notifikasi']
访问的,假设您的通知类是这样的,这会有所帮助:
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'notifikasi' => 'lorem ipsum'
];
}
如果通知支持存储在数据库表中,则应在通知类上定义toDatabase
方法。此方法将接收一个$notifiable
实体,并应返回一个纯PHP数组。返回的数组将被编码为JSON,并存储在notifications
表的data
列中。让我们来看一个示例toDatabase
方法:
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toDatabase($notifiable)
{
return [
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
];
}
访问通知
一旦通知存储在数据库中,您需要一种方便的方式从您的应通知实体访问它们。Laravel的默认AppUser
模型中包含的IlluminateNotificationsNotifiable
特性包括一个返回实体通知的notifications
Eloquent关系。要获取通知,您可以像访问任何其他Eloquent关系一样访问此方法。默认情况下,通知将按created_at
时间戳进行排序:
$user = AppUser::find(1);
foreach ($user->notifications as $notification) {
echo $notification->type;
}