laravel redirect if logged in

心不动则不痛 提交于 2019-12-14 03:39:27

问题


i am using laravel 5.1.8. i am making a login/registration system. i made a controller named AdminController and protect it with middleware.

but i am using laravel's default AuthController which methods and classes are located in different locations. where routes are:

Route::Controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController'
]);

get('admin', 'AdminController@index');
get('profile', 'AdminController@profile');
get('article', 'AdminController@article');

users cannot access AdminController without logging in. its redirected to login page. but i want, if a logged in user typed the address of login page or registration on the address bar of browser, the page will redirected to AdminController.

when i try to do this, it looking for '/home' and gives errors. i want to make it '/admin'.


回答1:


go to App\Http\Middleware\RedirectIfAuthenticated then change it from

public function handle($request, Closure $next)
{
    if ($this->auth->check()) {
        return redirect('/home');
    }

    return $next($request);
}

to

public function handle($request, Closure $next)
{
    if ($this->auth->check()) {
        return redirect('/admin');
    }

    return $next($request);
}



回答2:


Add this to your AuthController:

protected $redirectTo = '/admin';

This tells all the redirect methods in the various traits to redirect there instead of to /home.




回答3:


when a user is successfully authenticated, they will be redirected to the /home URI, which you will need to register a route to handle. You can customize the post-authentication redirect location by defining a redirectPath property on the AuthController:

protected $redirectPath = '/dashboard';




回答4:


Include \App\Http\Middleware\RedirectIfAuthenticated::class middleware in $middlewareGroups "web" array after \Illuminate\Session\Middleware\StartSession::class middleware

then modify your redirect path in handle() method of RedirectIfAuthenticated

public function handle($request, Closure $next, $guard = null)
    {
        //check if authenticate && second is condition when we need to redirect i.e, 
         if(Auth::guard($guard)->check() && $request->route()->named('login') ) {
        return redirect()->route('dashboard');
    }

        return $next($request);
    }



回答5:


You can check using auth function.

public function checkLogin()
{

    if (auth()->user()) 
    {
         return redirect(route('home'));
    }
    else
    {
           return redirect(route('login'));
    }
}


来源:https://stackoverflow.com/questions/32129874/laravel-redirect-if-logged-in

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