Laravel 5 检查用户是否登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30118234/
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-08 17:00:05  来源:igfitidea点击:

Laravel 5 check whether a user is logged in

authenticationlaravelfilterurl-routinglaravel-5

提问by Tartar

I am new to Laravel 5 and trying to understand its Authprocess. I want to prevent user to reach some of my pages unless the user is not logged in. Trying to make it with Route:filterbut it does not work. What i have done wrong ?

我是 Laravel 5 的新手并试图了解它的Auth过程。我想阻止用户访问我的某些页面,除非用户未登录。尝试使用Route:filter但它不起作用。我做错了什么?

Route::filter('/pages/mainpage', function()
{
    if(!Auth::check()) 
    {
        return Redirect::action('PagesController@index');
    }
});

回答by lukasgeiter

You should use the authmiddleware. In your route just add it like this:

您应该使用auth中间件。在您的路线中,只需像这样添加它:

Route::get('pages/mainpage', ['middleware' => 'auth', 'uses' => 'FooController@index']);

Or in your controllers constructor:

或者在您的控制器构造函数中:

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

回答by jorge gibbs

you can do this directly in your blade code by this way

您可以通过这种方式直接在刀片代码中执行此操作

@if (!Auth::guest())
        do this 
@else
        do that
@endif

回答by Ivan

use

Auth::check()

more here https://laravel.com/docs/5.2/authentication#authenticating-usersin Determining If The Current User Is Authenticated

更多在这里https://laravel.com/docs/5.2/authentication#authenticating-users确定当前用户是否经过身份验证

回答by Adnan

You can use middlewarein controller

您可以middleware在控制器中使用

  1. All actions in controller require to be logged in
  1. 控制器中的所有操作都需要登录
public function __construct()
{
    $this->middleware('auth');
}
  1. Or you can check it in action
  1. 或者你可以在行动中检查它
public function create()
{
    if (Auth::user()) {   // Check is user logged in
        $example= "example";
        return View('novosti.create')->with('example', $example);
    } else {
        return "You can't access here!";
    }
}
  1. Also you can use it on route
  1. 您也可以在路线上使用它
Route::get('example/index', ['middleware' => 'auth', 'uses' => 'example@index']);

回答by Khan Shahrukh

if you want authentication middleware for single route then

如果您想要单个路由的身份验证中间件,那么

// Single route

Route::get("/awesome/sauce", "AwesomeController@sauce", ['middleware' => 'auth']);

if you want auth middlesware on multiples routes then use :

如果您想在多条路线上使用身份验证中间件,请使用:

// Route group

Route::group(['middleware' => 'auth'], function() {
// lots of routes that require auth middleware
});