Laravel 5 检查用户是否登录

Laravel 5 check whether a user is logged in

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

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

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

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

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

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

如果你想要单一路由的认证中间件那么

// Single route

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

如果你想在多个路由上使用 auth 中间件,那么使用:

// Route group

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

您可以在控制器中使用middleware

  1. 控制器中的所有操作都需要登录
public function __construct()
{
    $this->middleware('auth');
}
  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. 你也可以在路线上使用它
Route::get('example/index', ['middleware' => 'auth', 'uses' => 'example@index']);

使用

Auth::check()

此处https://laravel.com/docs/5.2/authentication#authenticating-users的更多信息确定当前用户是否已通过身份验证

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

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

在 laravel 中,您可以检查用户是否已登录 blade 或未登录。 在第 blade 页中使用此代码:

@auth

    // The user is login...

@endauth


@guest

    // The user is not login...

@endguest

您也可以执行以下操作

@客人

//你想让客人看到什么就放这里

@else

//为特权用户保留的内容都在这里

@endguest

@guest
//Guest area
@else
//Privileged area
@endguest