Laravel 5检查用户是否已登录

Tar*_*tar 9 authentication url-routing filter laravel laravel-5

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

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

luk*_*ter 17

你应该使用auth中间件.在您的路线中,只需添加如下:

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

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

public function __construct(){
    $this->middleware('auth');
}
Run Code Online (Sandbox Code Playgroud)


小智 11

在 Laravel 中,您可以检查用户是否已登录 Blade 或未登录。 在页面刀片中使用以下代码:

@auth

    // The user is login...

@endauth


@guest

    // The user is not login...

@endguest
Run Code Online (Sandbox Code Playgroud)


Adn*_*nan 9

您可以middleware在控制器中使用

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


Iva*_*van 6

使用

Auth::check()
Run Code Online (Sandbox Code Playgroud)

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


小智 6

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

@if (!Auth::guest())
        do this 
@else
        do that
@endif
Run Code Online (Sandbox Code Playgroud)