Debug School

rakesh kumar
rakesh kumar

Posted on

How to render Dynamic Notification Data in Navbar Across Multiple Routes using middleware

To render dynamic notification data in the navbar across multiple routes using middleware in Laravel, follow these clear steps.
Step 1: Create Middleware
Use the Artisan command to generate your middleware class:


php artisan make:middleware InjectNotificationData
Enter fullscreen mode Exit fullscreen mode

Step 2: Implement Middleware Logic
In the generated file, implement logic to fetch and share notifications with all views:

<?php

namespace App\Http\Middleware;


use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Auth;
use App\Http\Controllers\Helpers\UtilityFunctionsController;

class InjectNotificationData
{

    protected $utilityController;

    // Dependency Injection in constructor
    public function __construct(UtilityFunctionsController $utilityController)
    {
        $this->utilityController = $utilityController;
    }

    public function handle(Request $request, Closure $next)
    {
        if (Auth::check() && Auth::user()->role == 'user') {
                 $user = Auth::user();
            // Fetch notification count and data here
           $notificationData = $this->utilityController->getUserNotificationData($user);

            // Share with all views
            View::share('notificationCount', $notificationData['count'] ?? 0);
            View::share('allNotifications', $notificationData['items'] ?? []);
        }
        return $next($request);
    }

}
Enter fullscreen mode Exit fullscreen mode

This makes $notificationCount and $allNotifications globally available to every Blade view rendered in that request.

Step 3: Register Middleware
Add your middleware to the $routeMiddleware array in app/Http/Kernel.php:

'inject.notifications' => \App\Http\Middleware\InjectNotificationData::class,
Enter fullscreen mode Exit fullscreen mode

This allows it to be used by name in your route definitions
*step4:Define getUserNotificationData function in utilitycontroller *

public function getUserNotificationData($user)
{
    // Fetch all notifications for the current user (adjust fields as needed)
     $notifications = Notification::with(['user', 'vendor', 'vehicle', 'shop', 'vehiclebyadmin'])
        ->where('user_id', $user->id)
        ->orderBy('id', 'desc')
        ->get();

    // Count the notifications
    $count = $notifications->count();

    // Return both the list and the count
    return [
        'count' => $count,
        'items' => $notifications
    ];
}
Enter fullscreen mode Exit fullscreen mode

step5:define miidleware on multiple route

Route::middleware(['auth', 'user-access:user' ,'inject.notifications'])->group(function () {

}

Route::middleware(['auth', 'user-access:vender','inject.notifications'])->prefix('partner')->group(function () {

}

Route::get('/searchvehicles', [Bookingcontroller::class, 'showVehicles'])
    ->middleware(['inject.notifications'])
    ->name('vehicles.index');
Enter fullscreen mode Exit fullscreen mode

output

Advantages

Automatic Data Injection
No manual data passing: No need to pass notification data manually from every controller to every view.

Always Up-to-Date
Consistent and real-time: Keeps notification counts and lists updated across all relevant pages, as user navigates.

Centralized Logic
Easy maintenance: Notification-fetching logic is centralized, making future changes easy and bug-free.

Seamless User Experience
Uniform UI: No matter which page is visited (dashboard, orders, bookings, etc.), the navbar bell and count accurately reflect user notifications:

Example: The “rakesh” user sees correct notification count (4) in both dashboard and orders pages.

Top comments (0)