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

iambaz's avatar

How to use Auth middleware in my own package

I have created a new package with some custom routes. Within these routes I need to access the Auth::id(). I have wrapped the routes with the usual auth middleware like so:

Route::group(['middleware' => 'auth'], function(){

    Route::get('/importer', '\Vendor\Package\Controllers\ImporterController@index');
    Route::post('/importer/import', '\Vendor\Package\Controllers\ImporterController@import');

});

When I navigate to any of my routes, I am redirected to /home even whilst logged in.

Do I need to register something in my package to set up the authentication environment?

0 likes
4 replies
iambaz's avatar
iambaz
OP
Best Answer
Level 2

I worked this out - seems I had to add the web guard to the route group like so:

Route::group(['middleware' => ['web', 'auth']], function(){

    Route::get('/importer', '\Vendor\Package\Controllers\ImporterController@index');
    Route::post('/importer/import', '\Vendor\Package\Controllers\ImporterController@import');

});
13 likes
Tetravalence's avatar

@iambaz You did resolve my problem. Thank you.

Does anyone know why this code below is not working?

Route::middleware('web', 'auth', 'dashboard')->group(function () {
    Route::get('/dashboard', 'MypackageDashboardController@index');
    Route::get('/dashboard/template', 'MypackageDashboardController@template')->name('template');
});

While this one is correct

Route::group(['middleware' => ['web', 'auth', 'dashboard']], function () {
  Route::get('/dashboard', 'MypackageDashboardController@index');
  Route::get('/dashboard/template', 'MypackageDashboardController@template')->name('template');
});
massimoselvi's avatar

@Tetravalence Because the middleware method accept 1 argument that could only be: array OR string OR null

    /**
     * Get or set the middlewares attached to the route.
     *
     * @param  array|string|null  $middleware
     * @return $this|array
     */

so those 3 arguments should be passed as array: ['web', 'auth', 'dashboard']

Route::middleware(['web', 'auth', 'dashboard'])->group(function () {
    Route::get('/dashboard', 'MypackageDashboardController@index');
    Route::get('/dashboard/template', 'MypackageDashboardController@template')->name('template');
});

Please or to participate in this conversation.