简体   繁体   中英

Laravel redirect based on role - spatie/laravel-permission

I am using this package spatie/laravel-permission and what I want to do is:

super-admin, admin, members have the same login and after logged in it redirect to different routes. The super-admin and admin have the same redirect. So I put this code.

//app\Http\Controllers\Auth\LoginController.php
protected function authenticated(Request $request, $user)
{
    if ( $user->hasAnyRole(['super-admin', 'admin']) ) {// do your margic here
        return redirect()->route('admin.dashboard');
    }

     return redirect('/home');
}

and then this is my routes //routes/web.php

Auth::routes();
Route::group(['middleware' => ['role:member']], function () {
    Route::get('/', 'HomeController@index')->name('home');
});
Route::group(['middleware' => ['role:super-admin|admin'], 'prefix' => 'admin'], function () {
    Route::get('/', 'Admin\HomeController@dashboard')->name('admin.dashboard');
});

After login, what I want to do is when a super-admin / admin visit the site.com/* it should redirect to site.com/admin/ cause he is not authorize cause he is not a member and also when a member visit the site.com/admin/* , he redirect to site.com/ cause he is not admin/super-admin , the rest will go to login page when not authenticated.

It displays like this, 图片

It should redirect based on their role homepage instead display 403 error.

Well, based on the package's middleware , there's no redirection logic involved. It is just checking if it has the correct permissions and throwing an unauthorized exception if the user does not.

You would need to write your own custom middleware, where you will check whether the user has the appropriate roles and to redirect to the appropriate url. A very simplistic example would be something like this (in the case of an admin).

<?php

namespace App\Http\Middleware;

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

class CheckIfAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if ( $user->hasAnyRole(['super-admin', 'admin']) ) {
            return $next($request);
        }

        return redirect('/');
    }
}

You would then attach this middleware instead of the other one.

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