Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SlimDeluxe's avatar

Route not working for package controller with auth middleware

I am having trouble with setting up routes for a controller that is in a package and uses the auth middleware.

I have the following in the package ServiceProvider:

    public function boot()
    {
        $package_dir = __DIR__ .'/../../';

        $this->loadRoutesFrom($package_dir .'routes/web.php');
        $this->loadViewsFrom($package_dir .'resources/views', 'core');
    }

In the package's own routes/web.php:

Route::resource('/users', '\Ocelot\Core\Http\Controllers\UsersController')->middleware('auth');
//Route::get('/users', '\Ocelot\Core\Http\Controllers\UsersController@index')->middleware('auth');
//Route::get('/users', [\Ocelot\Core\Http\Controllers\UsersController::class, 'index'])->middleware('auth');

Neither of these variants work, until I remove ->middleware('auth'). The same applies if I set the middleware in the controller constructor:

    public function __construct()
    {
        $this->middleware('auth');
    }

What happens is that when I visit /users I get the following trace

  1. /users 302 redirect to ...
  2. /login 302 redirect to ...
  3. /home

However, if I put Route::resource('/users', '\Ocelot\Core\Http\Controllers\UsersController')->middleware('auth');into the application root routes/web.php the exact same code works as expected.

I am on Laravel version 6.9.0. Please also note...

  1. I use a custom table name for the users table
  2. My User class is also in the package and not in App\User
  3. The whole time I am not logged out or something - the session is stable

For some reason, the Illuminate\Auth\Middleware\Authenticate::authenticate() method thinks I am not authorized and dd's a Null here

protected function authenticate($request, array $guards)
    {
        if (empty($guards)) {
            $guards = [null];
        }

        foreach ($guards as $guard) {
            if ($this->auth->guard($guard)->check()) {
                return $this->auth->shouldUse($guard);
            }
        }

        dd(\Illuminate\Support\Facades\Auth::user());
        $this->unauthenticated($request, $guards);
    }

The Http Kernel is untouched since install:

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];

    /**
     * The priority-sorted list of middleware.
     *
     * This forces non-global middleware to always be in the given order.
     *
     * @var array
     */
    protected $middlewarePriority = [
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];
}

Am I missing something or have I discovered a bug? :)

Related: https://laracasts.com/discuss/channels/code-review/package-controller-not-called-when-using-middlewareauth-while-signed-in

0 likes
10 replies
bobbybouwmann's avatar

Mmh, I don't think this is a bug at all. I think your login process is not correct. The package looks fine to me, it just seems that you're not logged in when accessing the route of your package.

Whenever I created a package with authentication I always created a custom guard, but I can understand that, in your case, this is not an option.

So, are you logged in on other routes of the application itself?

SlimDeluxe's avatar

Sorry, I forgot to add that I am using the laravel ui package and deployed the auth scaffolding. I haven't written or changed anything there yet, apart from the config.

So yes, I am logged in. To test this, apart from the HomeController where it works, I added another TestController:

class TestController extends Controller
{
    public function index()
    {
        echo Auth::user()->email;
    }
}

... and this echoes my email. But as soon as I go back to /users, the 1-3 redirect occurs.

Also note, as I've said, just moving the Route declaration from the package routes file to the global routes file makes everything work as expected.

SlimDeluxe's avatar

Another thing, in the package UsersController.php, if I try to dd the User, I get a null, if the route is defined in the package. If I move it to the global routes file, it dumps it correctly.

    public function index()
    {
        dd(Auth::user());
        return view('core::users/users', [
            'users' => User::all(),
        ]);
    }
SlimDeluxe's avatar

Also tried this in my ServiceProvider, as seen in TelescopeServiceProvider

public function boot()
    {
        $package_dir = __DIR__ .'/../../';

        Route::group([
            'namespace' => 'Ocelot\Core\Http\Controllers',
            //'middleware' => 'auth',
        ], function() use($package_dir) {
            $this->loadRoutesFrom($package_dir .'routes/web.php');
        });
    }

Works perfectly until I un-comment the middleware paramerer.

Bottom line, no matter where I apply the middleware, it just won't work, except in the global routes file.

SlimDeluxe's avatar

If I'm not properly logged in, why does step 2 - /login redirect me to home then? Why can I see the user with Auth::user()?

It's not "my" authentication, it's the one that shipped with Laravel.

sujancse's avatar

Then try clearing your route-cache like php artisan route:clear

SlimDeluxe's avatar

Yes, that's it, it works now :D

Route::resource('/users', '\Ocelot\Core\Http\Controllers\UsersController')->middleware(['web', 'auth']);

Thanks!

Please or to participate in this conversation.