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
Laravel 5 check whether a user is logged in
提问by Tartar
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 ?
我是 Laravel 5 的新手并试图了解它的Auth
过程。我想阻止用户访问我的某些页面,除非用户未登录。尝试使用Route:filter
但它不起作用。我做错了什么?
Route::filter('/pages/mainpage', function()
{
if(!Auth::check())
{
return Redirect::action('PagesController@index');
}
});
回答by lukasgeiter
You should use the auth
middleware. 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 middleware
in controller
您可以middleware
在控制器中使用
- All actions in controller require to be logged in
- 控制器中的所有操作都需要登录
public function __construct()
{
$this->middleware('auth');
}
- 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!";
}
}
- Also you can use it on route
- 您也可以在路线上使用它
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
});