0
votes

I'd like to pre check two different Route Groups by the auth:admin middleware. This works perfectly for the first Route Group inside but not for the second which is in an other Namespace.

My Routes file looks like this:

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

    Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.'], function(){
        Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
    });

    Route::group(['prefix' => 'team/{team_id}', 'namespace' => 'Team', 'as' => 'team.'], function(){
        Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
    });

});

If I'm not logged in and try to go to admin/dashboard, I'm redirected to login/admin. But if I try to go to team/1/dashboard it says Error 'Trying to get property 'headers' of non-object'. How can I get the auth:admin Middleware to work with my Team Routes too?

1

1 Answers

0
votes

create a middleware

class IsAdmin
{
    public function handle($request, Closure $next)
    {
        if (Auth::user()->permission == 'admin') {
            return $next($request);
        }

        return redirect()->route('some.route'); // If user is not an admin.
    }
}

Register in kernel.php

protected $routeMiddleware = [ .... 'is.admin' => \App\Http\Middleware\IsAdmin::class, ];

So your routes:

Route::group(['middleware' => 'is.admin'], function () {
Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.'], function(){
        Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
    });

    Route::group(['prefix' => 'team/{team_id}', 'namespace' => 'Team', 'as' => 'team.'], function(){
        Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
    });
});