dongxun3424 2017-10-30 14:29
浏览 22
已采纳

Laravel对所选角色的路线限制

I have a users table with two types of users: Vendor and Customer. Every thing is fine with login if vendor role is 1 redirect to vendor Dashboard and for customer role is 2 redirect to customer dashboard but after login how to prevent route to customer dashboard if logged as vendor and vice versa Controller for login depend on role:

class CustomerLoginController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest:web');
    }

    public function showLoginForm()
    {
        return view('Customer.login');
    }

    public function login(Request $request)
    {
        $this->validate($request,[
            'email'=>'required|email',
            'password'=>'required|min:6',
        ]);

        if (Auth::guard('web')->attempt(['email'=>$request->email,'password'=>$request->password,'active'=>1,'role_id'=>2], $request->remember)) {

            return redirect()->intended(route('customer.dashboard'));

        } elseif (Auth::guard('web')->attempt(['email'=>$request->email,'password'=>$request->password,'active'=>1,'role_id'=>1],$request->remember)) {
            return redirect()->intended(route('vendor.dashboard'));

        }
        return redirect()->back()->withInput($request->only('email','remember'));
    }

}

after login route controller:

public function __construct()
{
    $this->middleware('auth');
}
public function index()
{
    return view('index.customer.customerdashboard');
}

public function vendor()
{
    return view('index.vendor.vendordashboard');
}
  • 写回答

1条回答 默认 最新

  • dongying3830 2017-10-30 14:52
    关注

    You need to create a middleware with

    php artisan make:middleware PortectedVendorRoutesMiddleware
    

    Then, in the handle method of that file, add the logic to check for the user's role

    public function handle($request, Closure $next)
    {
        if (auth()->user()->role_id == 1) {
           return $next($request);
        }
    
    
        abort(404);
    }
    

    Now you need to protect your routes

    Route::group(['middleware' => App\Http\Middleware\ProtectVendorRoutesMiddleware::class], function () {
    
        // Your protected vendor routes here
    });
    

    Or since Laravel 5.5

    Route::middleware([App\Http\Middleware\ProtectVendorRoutesMiddleware::class])->group(function () {
    
        // Your protected vendor routes here
    });
    

    Repeat the process for Customer routes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应