简体   繁体   中英

Laravel Route Middleware auth:admin not working for all Routes

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?

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']);
    });
});

check app/Http/Controllers/Middleware/RedirectIfAuthenticated.php file and update the code for different guard use

// app/Http/Controllers/Middleware/RedirectIfAuthenticated.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    public function handle($request, Closure $next, $guard = null)
    {
        if ($guard == "admin" && Auth::guard($guard)->check()) {
            return redirect('/admin');
        }
        if ($guard == "writer" && Auth::guard($guard)->check()) {
            return redirect('/writer');
        }
        if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }

        return $next($request);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM