use native Laravel notification methods

This commit is contained in:
2026-03-28 16:41:38 +01:00
parent 4c52fa5043
commit 60760d6101
@@ -2,58 +2,49 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Illuminate\Support\Facades\Notification;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
class NotificationsController extends Controller class NotificationsController extends Controller
{ {
public function getNotifications(Request $request): JsonResponse { public function getNotifications(Request $request): JsonResponse
{
try { try {
$notif = $request->user() $notifications = $request->user()
->notifications() ->notifications()
->latest() ->latest()
->get(); ->get();
return response()->json([ return response()->json(['data' => $notifications]);
'data' => $notif } catch (\Exception $e) {
]); Log::error($e->getMessage());
} catch(\Exception $e) { return response()->json(['message' => 'Server error'], 500);
Log::info($e->getMessage());
return response()->json(['message' => "Server error"], 500);
} }
} }
public function deleteNotification(Request $request, int $notificationId): JsonResponse
{
public function deleteNotification(Request $request, int $notificationId): JsonResponse {
try { try {
$request->user()->notifications()->detach($notificationId); $notification = $request->user()->notifications()->findOrFail($notificationId);
$notification->delete();
$notification = Notification::find($notificationId);
if ($notification && $notification->users()->count() === 0) {
$notification->delete();
}
return response()->json(['message' => 'Notification supprimée avec succès']); return response()->json(['message' => 'Notification supprimée avec succès']);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::info($e->getMessage()); Log::error($e->getMessage());
return response()->json(['message' => 'Erreur lors de la suppression'], 500); return response()->json(['message' => 'Erreur lors de la suppression'], 500);
} }
} }
public function readNotifications(Request $request): JsonResponse { public function readNotifications(Request $request): JsonResponse
{
try { try {
$user = $request->user(); $request->user()->unreadNotifications->markAsRead();
$notificationIds = $user->notifications()->pluck('notification_id');
$user->notifications()->updateExistingPivot($notificationIds, ['unread' => 0]); return response()->json(['message' => 'Notifications marquées comme lues']);
} catch (\Exception $e) {
return response()->json(['message' => "Notifications marquées comme lues"], 200); Log::error($e->getMessage());
} catch(\Exception $e) { return response()->json(['message' => 'Server error'], 500);
Log::info($e->getMessage());
return response()->json(['message' => "Server error"], 500);
} }
} }
} }