Files
SAE-BUT2-backend/app/Http/Controllers/NotificationsController.php
T

58 lines
1.6 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Notification;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class NotificationsController extends Controller
{
public function createNotification(Request $request, int $id): JsonResponse {
$notification = Notification::create([
"content" => $request["content"]
]);
$notification->users()->attach($id);
return response()->json(['message' => 'Notification created successfully']);
}
public function getNotifications(Request $request, int $id): JsonResponse {
try {
$user = User::findOrFail($id);
return response()->json([
'data' => $user->notifications
]);
} catch(\Exception $e) {
Log::info($e->getMessage());
return response()->json(['message' => "Server error"], 500);
}
}
public function deleteNotification(int $userId, int $notificationId): JsonResponse {
try {
$user = User::findOrFail($userId);
$user->notifications()->detach($notificationId);
$notification = Notification::find($notificationId);
if ($notification && $notification->users()->count() === 0) {
$notification->delete();
}
return response()->json(['message' => 'Notification supprimée avec succès']);
} catch (\Exception $e) {
Log::info($e->getMessage());
return response()->json(['message' => 'Erreur lors de la suppression'], 500);
}
}
}