how to check if user is logged in by his session in route and then call controller method in laravel?

為{幸葍}努か 提交于 2019-12-14 02:03:43

问题


I'm using Laravel 5.2. I want to check user session in routes file, so that if session is set user can visit dashboard otherwise redirect to login page.

I have used following code for this but it's not working. It's not giving any error and not redirecting him to login page. anyhow if I write same code in controller functioin, it works fine.

Route::group(['middleware' => ['web']], function () {
    Route::get('dashboard/index', ['uses' => 'DashboardController@index'], function() {
    $value = $request->session()->get('name', 'not_loggin');
    if ($value == 'not_loggin') {
        return redirect('/user/login');
    }
    });
});

it also didn't worked if I write it in constructor.


回答1:


You should use the auth middleware:

Route::get('dashboard/index', [
   'middleware' => 'auth',
   'uses' => 'DashboardController@index'
]);


来源:https://stackoverflow.com/questions/35775014/how-to-check-if-user-is-logged-in-by-his-session-in-route-and-then-call-controll

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