From 440f6b14f9e3f62c6e6fc80496fcf5f61917e04d Mon Sep 17 00:00:00 2001 From: Tareq Hasan Date: Tue, 19 Mar 2024 14:34:36 +0600 Subject: [PATCH] feat: notify users on comment creation --- .../Frontend/CommentController.php | 27 ++++++++- app/Notifications/CommentNotification.php | 56 +++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 app/Notifications/CommentNotification.php diff --git a/app/Http/Controllers/Frontend/CommentController.php b/app/Http/Controllers/Frontend/CommentController.php index 494270e..c5afabb 100644 --- a/app/Http/Controllers/Frontend/CommentController.php +++ b/app/Http/Controllers/Frontend/CommentController.php @@ -2,9 +2,13 @@ namespace App\Http\Controllers\Frontend; -use App\Http\Controllers\Controller; use App\Models\Post; +use App\Models\User; +use App\Models\Comment; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Log; +use App\Http\Controllers\Controller; +use App\Notifications\CommentNotification; class CommentController extends Controller { @@ -54,9 +58,30 @@ public function store(Request $request, Post $post) 'parent_id' => $parentId === 0 ? null : $parentId, ]); + $this->notifyUsers($post, $comment); + $comment->load('user'); $comment->children = []; return response()->json($comment); } + + private function notifyUsers(Post $post, Comment $comment) + { + $userIds = $post->comments() + ->where('user_id', '!=', $comment->user_id) + ->pluck('user_id') + ->merge($post->votes()->where('user_id', '!=', $comment->user_id)->pluck('user_id')) + ->unique(); + + if ($userIds->isEmpty()) { + return; + } + + $users = User::whereIn('id', $userIds)->get(); + + foreach ($users as $user) { + $user->notify(new CommentNotification($post, $comment)); + } + } } diff --git a/app/Notifications/CommentNotification.php b/app/Notifications/CommentNotification.php new file mode 100644 index 0000000..ce580df --- /dev/null +++ b/app/Notifications/CommentNotification.php @@ -0,0 +1,56 @@ + + */ + public function via(object $notifiable): array + { + return ['mail']; + } + + /** + * Get the mail representation of the notification. + */ + public function toMail(object $notifiable): MailMessage + { + return (new MailMessage()) + ->line('The introduction to the notification.') + ->action('Notification Action', url('/')) + ->line('Thank you for using our application!'); + } + + /** + * Get the array representation of the notification. + * + * @return array + */ + public function toArray(object $notifiable): array + { + return [ + // + ]; + } +}