如果用户未登录 Laravel,则重定向到登录页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30918270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:48:11  来源:igfitidea点击:

Redirect to Login page if ther user not logged in Laravel

laravellaravel-5laravel-routing

提问by Praveen Srinivasan

I am using Laravel version 5. I have a route file for my project which contains plenty of lines. I need to put authentication like Redirect to login page if the user is not logged in. And I also want to prevent direct URL access if the user not logged in. What can I do?

我使用的是 Laravel 版本 5。我的项目有一个路由文件,其中包含很多行。如果用户未登录,我需要将诸如重定向之类的身份验证置于登录页面。如果用户未登录,我还想阻止直接 URL 访问。我该怎么办?

And I have used below code

我使用了下面的代码

Route::group(array('before' => 'auth'), function(){
    Route::get('/', 'HomeController@index');
});

But this prevents only for home page. I need to protect All my routes. And also suggest me how to reduce route file lines.

但这只能防止主页。我需要保护我所有的路线。并建议我如何减少路由文件行。

回答by baao

You can put as many routes in a Group as you like to

您可以根据需要在 Group 中放置任意数量的路由

Route::group(array('before' => 'auth'), function(){
    Route::get('/', 'HomeController@index');
    Route::post('store', 'HomeController@store');
    Route::get('show', 'AnotherController@index');
    // ...
});

If you really need to protect allyour routes, you could add

如果您确实需要保护所有路线,则可以添加

 public function __construct()
 {
      $this->middleware('auth');
 }

To your main controller class, Http/Controllers/Controller

对于您的主控制器类, Http/Controllers/Controller

Edit for your comment, taken from the docs, you may use

编辑您的评论,取自docs,您可以使用

return redirect()->intended('view');

return redirect()->intended('view');

/**
 * Handle an authentication attempt.
 *
 * @return Response
 */
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password]))
        {
            return redirect()->intended('dashboard');
        }
    }

}