SigalZ's avatar

Middleware does not recognize logged user

Using Laravel 12, I have a custom routes file.

All the routes in this file should be blocked to guests and users that don't have a specific permission.

I can't make the middlware work correctly.

The user I am testing has the permission 'admin dashboard' through the 'admin' role.

The routes file: routes/admin.php:

use Illuminate\Support\Facades\Route;

Route::get('/dashboard', function () {
dd('admin');
})->name('dashboard');

In bootstrap/app.php:

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
        then: function () {

            Route::middleware( 'admin')

                ->prefix('admin')

                ->name('admin.')

                ->group(base_path('routes/admin.php'));
        },

    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
        $middleware->append(ProtectAgainstSpam::class);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

In App/Http/Middleware/AdminMiddleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;

class AdminMiddlware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
//Tried
        if (! $request->user() || ! $request->user()->can('admin dashboard')) {
//And Tried
		if (! Auth::user() || ! Auth::user()->can('admin dashboard')) {
            abort(403, 'Unauthorized action.'); // Or redirect to a different page
        }
		
        return $next($request);
    }
}

Even though the user is logged in and has the permission, I get the Unauthorized page.

using: dd(Auth::user()) or dd($request->user()) both return null.

Can anyone help please?

0 likes
5 replies
JussiMannisto's avatar

The user isn't recognized because your admin routes don't boot up sessions.

You're defining the admin routes in a callback without the web middleware stack, which includes the StartSession middleware. A quick and dirty fix is to add the web middleware stack in the callback:

Route::middleware(['web', 'admin'])
	->...

But a better approach is to follow the convention of loading the routes directly in web.php:

require __DIR__.'/admin.php';

And defining the prefixes etc. in the admin route file itself:

Route::middleware('admin')->prefix('admin')->name('admin.')->group(function () {
	// Routes here.
});
SigalZ's avatar

Thank you.

I tried your second solution so now my web.php has this code:

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\ContactController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PagesController;

Auth::routes();

require __DIR__ . '/admin.php';

Route::get('/', [HomeController::class, 'index'])->name('home');

My admin.php file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Middleware\AdminMiddlware;

Route::middleware(AdminMiddlware::class)->prefix('admin')->name('admin.')->group(function () {
    dd('admin');
})->name('dashboard');

app.php

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
        /*then: function () {

            Route::middleware(AdminMiddlware::class)
                ->prefix('admin')
                ->name('adminn.')
                ->group(base_path('routes/admin.php'));
        },*/

    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
        $middleware->append(ProtectAgainstSpam::class);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

Now I can't browse anywhere besides the admin dashboard, e.g. if I put the sites home page in the browser's address, it still goes to the admin route instead of the home page and I get this error on VS code:

2025-11-24 11:24:00.382 [info] Laravel Extra Intellisense command started: Application Models 2025-11-24 11:24:00.383 [info] Laravel Extra Intellisense command started: Auth Data 2025-11-24 11:24:02.053 [error] Laravel Extra Intellisense Error: Auth Data

"admin" // routes\admin.php:14

2025-11-24 11:24:02.059 [error] Laravel Extra Intellisense Error: Application Models

"admin" // routes\admin.php:14

Can you please help?

JussiMannisto's avatar

Nothing goes to an admin route; you're crashing the app when Laravel is trying to register routes:

dd('admin');

Add the route definitions instead of a dd() call.

1 like
SigalZ's avatar

Ok, I found a way to make it all work.

In the app.php file I add the admin.php route file into the web route:

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: [
            __DIR__ . '/../routes/web.php',
            __DIR__ . '/../routes/admin.php'
        ],

And in my admin.php I removed the dd('admin') which caused errors and put a route call to a controller:

Route::middleware(AdminMiddlware::class)->prefix('admin')->name('admin.')->group(function () {
    Route::get('/dashboard', [AdminController::class, 'index'])->name('dashboard');
});

Please or to participate in this conversation.