feat: add persistent mobile notifications
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Resources\NotificationResource;
|
||||
use App\Notifications\MobileNotification;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
|
||||
class NotificationController extends Controller
|
||||
{
|
||||
public function index(Request $request): AnonymousResourceCollection
|
||||
{
|
||||
$perPage = max(1, min($request->integer('per_page', 20), 60));
|
||||
$notifications = $request->user()
|
||||
->notifications()
|
||||
->whereIn('type', MobileNotification::TYPES)
|
||||
->latest()
|
||||
->paginate($perPage);
|
||||
|
||||
return NotificationResource::collection($notifications)->additional([
|
||||
'unreadCount' => $this->unreadCountFor($request),
|
||||
]);
|
||||
}
|
||||
|
||||
public function unreadCount(Request $request): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'data' => [
|
||||
'count' => $this->unreadCountFor($request),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function markAsRead(Request $request, string $notification): NotificationResource
|
||||
{
|
||||
$databaseNotification = $request->user()
|
||||
->notifications()
|
||||
->whereIn('type', MobileNotification::TYPES)
|
||||
->findOrFail($notification);
|
||||
|
||||
$databaseNotification->markAsRead();
|
||||
|
||||
return NotificationResource::make($databaseNotification->fresh());
|
||||
}
|
||||
|
||||
public function markAllAsRead(Request $request): JsonResponse
|
||||
{
|
||||
$updated = $request->user()
|
||||
->unreadNotifications()
|
||||
->whereIn('type', MobileNotification::TYPES)
|
||||
->update(['read_at' => now()]);
|
||||
|
||||
return response()->json([
|
||||
'data' => [
|
||||
'updated' => $updated,
|
||||
],
|
||||
'message' => __('api.notifications.all_read'),
|
||||
]);
|
||||
}
|
||||
|
||||
private function unreadCountFor(Request $request): int
|
||||
{
|
||||
return $request->user()
|
||||
->unreadNotifications()
|
||||
->whereIn('type', MobileNotification::TYPES)
|
||||
->count();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user