Skip to content

Commit

Permalink
feat: notify users on comment creation
Browse files Browse the repository at this point in the history
  • Loading branch information
tareq1988 committed Mar 19, 2024
1 parent ec8250d commit 440f6b1
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
27 changes: 26 additions & 1 deletion app/Http/Controllers/Frontend/CommentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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));
}
}
}
56 changes: 56 additions & 0 deletions app/Notifications/CommentNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace App\Notifications;

use App\Models\Comment;
use App\Models\Post;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class CommentNotification extends Notification
{
use Queueable;

/**
* Create a new notification instance.
*/
public function __construct(protected Post $post, protected Comment $comment)
{
//
}

/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
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<string, mixed>
*/
public function toArray(object $notifiable): array
{
return [
//
];
}
}

0 comments on commit 440f6b1

Please sign in to comment.