Laravel如何实现帖子评论通知聚合,多条通知时自动修改展示数值
Laravel 同帖子未读评论通知累计功能实现方案
1. 调整notifications表结构
默认Laravel生成的通知表缺少关联目标标识和计数字段,先新增字段:
- 生成迁移文件:
php artisan make:migration add_related_fields_to_notifications_table - 迁移文件核心逻辑:
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up() { Schema::table('notifications', function (Blueprint $table) { // 标识通知关联的业务对象 $table->string('target_type')->nullable()->index(); $table->unsignedBigInteger('target_id')->nullable()->index(); // 存未读通知累计数量 $table->unsignedInteger('unread_count')->default(1); }); } public function down() { Schema::table('notifications', function (Blueprint $table) { $table->dropColumn(['target_type', 'target_id', 'unread_count']); }); } };
- 执行迁移:
php artisan migrate
2. 修改AlarmNotification类
补充构造参数和数据库字段赋值逻辑:
<?php namespace App\Notifications; use App\Models\Post; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; class AlarmNotification extends Notification { use Queueable; public Post $post; public int $count; // 接收关联帖子和初始计数 public function __construct(Post $post, int $count = 1) { $this->post = $post; $this->count = $count; } public function via($notifiable) { return ['database']; } public function toDatabase($notifiable) { return [ 'target_type' => Post::class, 'target_id' => $this->post->id, 'unread_count' => $this->count, 'message' => $this->count === 1 ? '有新评论' : "有{$this->count}条新评论", 'post_id' => $this->post->id, // 可补充其他业务需要的字段 ]; } }
3. 新增评论时的通知逻辑调整
不要直接调用notify方法,先判断是否存在同帖子的未读评论通知:
// 以下代码放在评论创建成功后的逻辑中,比如评论控制器store方法、评论创建事件监听器内 // $comment 为当前新创建的评论实例 $post = $comment->post; $postAuthor = $post->user; // 查询是否存在同个帖子的未读评论通知 $existsNotification = $postAuthor->notifications() ->where('type', AlarmNotification::class) ->where('target_type', Post::class) ->where('target_id', $post->id) ->whereNull('read_at') ->first(); if ($existsNotification) { // 存在则更新计数和通知内容 $newCount = $existsNotification->unread_count + 1; $existsNotification->update([ 'unread_count' => $newCount, 'data' => array_merge($existsNotification->data, [ 'unread_count' => $newCount, 'message' => "有{$newCount}条新评论" ]), 'updated_at' => now() ]); } else { // 不存在则新建通知 $postAuthor->notify(new AlarmNotification($post)); }
4. 前端展示适配
渲染通知时直接读取notification.data.message字段展示即可,用户标记通知为已读后,后续新评论会自动生成新的通知条目,符合业务逻辑。
该逻辑可直接扩展到点赞、其他同类型累计通知场景,仅需调整target_type对应的模型类即可。
内容的提问来源于stack exchange,提问作者Macfa
相关产品推荐
相关产品推荐

