Laravel 5 check whether a user is logged in

两盒软妹~` 提交于 2019-12-21 09:20:08

问题


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

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

回答1:


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

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

Or in your controllers constructor:

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



回答2:


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

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




回答3:


use

Auth::check()

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




回答4:


You can use middleware in controller

  1. All actions in controller require to be logged in
public function __construct()
{
    $this->middleware('auth');
}
  1. Or you can check it in action
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
Route::get('example/index', ['middleware' => 'auth', 'uses' => 'example@index']);



回答5:


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
});


来源:https://stackoverflow.com/questions/30118234/laravel-5-check-whether-a-user-is-logged-in

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