Middleware, how to redirect after check Laravel 5

戏子无情 提交于 2019-12-30 04:35:30

问题


I need after check if user is logged as editor, to redirect to profile page...

Here is my code:

<?php namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

use Closure;

class AdminMiddleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check()){
                    if(Auth::user()->roles->toArray()[0]['role'] == 'editor'){
                       return redirect('/profile');
                    }
                    return $next($request);
                }
                else
                {

                   return $next($request);
                }
    }

}

Problem with this code is when user is editor I get infinite loop....

Here is my routs:

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

    Route::get('home', ['middleware' => 'admin', function()
        {
        return view('home');
        }]);
    Route::get('profile', array(
       'as' => 'profile',
       'uses' => 'UserController@getProfile'
    ));


});

Anyone know what is problem?


回答1:


Where did you register your middleware in App\Http\Kernel?

Is it in protected $middleware = [] or protected $routeMiddleware = [] ?

If registered in $middleware it will run on each very request thereby causing infinite loop, if so use only $routeMiddleware




回答2:


I found this to be a less code and less decisions for redirecting users based on roles, Put this in your AuthController.php

protected function authenticated( $user)
{

    if($user->user_group == '0') {
        return redirect('/dashboard');
    }

    return redirect('my-account');
}

https://laracasts.com/discuss/channels/laravel/how-best-to-redirect-admins-from-users-after-login-authentication




回答3:


Go to Kernel.php. It's in app\http. Try to find protected $routeMiddleware in that array you need to add this

'admin' => \App\Http\Middleware\AdminMiddleware::class

After that it should work fine. Hope this helps anyone who faces the same problem.



来源:https://stackoverflow.com/questions/29062680/middleware-how-to-redirect-after-check-laravel-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!