原理:
在通知列表中,如果已读,直接链接到原本的url;如果未读,先跳转到notifications/n_id将此通知设置为已读,在链接到redirect_url(原本的url)。使用 notifications/n_id?redirect_url=xxx的形式
在laravel 5.3.30+ 中vendor\laravel\framework\src\Illuminate\Notifications\DatabaseNotification.php
有read、unread、markAsRead
<?php
namespace Illuminate\Notifications;
use Illuminate\Database\Eloquent\Model;
class DatabaseNotification extends Model
{
public $incrementing = false;
protected $table = 'notifications';
protected $guarded = [];
protected $casts = [
'data' => 'array',
'read_at' => 'datetime',
];
public function notifiable()
{
return $this->morphTo();
}
public function markAsRead()
{
if (is_null($this->read_at)) {
$this->forceFill(['read_at' => $this->freshTimestamp()])->save();
}
}
public function read()
{
return $this->read_at !== null;
}
public function unread()
{
return $this->read_at === null;
}
public function newCollection(array $models = [])
{
return new DatabaseNotificationCollection($models);
}
}
步骤:
1、列表显示
<li class="notifications {{$notification->unread() ? 'unread' : ''}}">
<a
@if($notification->unread())
href="/notifications/{{$notification->id}}?redirect_url=/inbox/{{$notification->data['dialog']}}"
@else
href="/inbox/{{$notification->data['dialog']}}"
@endif
>{{$notification->data['name']}}
给您发送了一条私信
</a>
</li>
2、路由
Route::get('/notifications/{notification}','NotificationsController@show');
3、NotificationsController
public function show(DatabaseNotification $notification)//注入
{
$notification->markAsRead(); //设置为已读
return redirect(\Request::query('redirect_url'));
}