如何检查用户是否登录并相应地重定向

时间:2014-12-29 12:05:22

标签: php authentication laravel laravel-4

这是我的路线:

Route::get('/', 'HomeController@home');
Route::post('login', 'LoginController@Login');
Route::get('vehicle', 'VehicleController@VehicleLayout');

到目前为止,任何用户都可以访问所有页面。

我开始使用auth::user所以

    if (Auth::attempt($LoginData))
    {
        return Redirect::intended('dashboard');
    }
    else
    {
        return Redirect::to('')->with('Message', 'UserName or Password Invalid');
    }

我正在登录登录屏幕。

但是从上面的代码中可以看出来。可以从任何位置访问页面vehicle。我在{{ Auth::user()->FirstName}}

收到了用户的详细信息

当我尝试访问车辆页面时,如果用户没有登录,则只会抛出错误

Trying to get property of non-object (View: C:\xampp\htdocs\mti\app\views\layouts\dashboardlayout.blade.php) (View: C:\xampp\htdocs\mti\app\views\layouts\dashboardlayout.blade.php)

有没有办法检查用户是否已登录并将用户重定向到登录页面,但是有错误的方式。

<?php
if (Auth::guest())
{
    return Redirect::to('logout')->with('Message', 'You Must Logged In to Access this page.');
}
?>

上面给出了一个好的过程,还是有任何laravel方式来做到这一点。

2 个答案:

答案 0 :(得分:1)

您可以而且应该使用filters。甚至还有一个内置auth filter(你可以在app/filters.php内找到它)

与路线组合使用效果非常好。这是一个例子:

Route::group(array('before' => 'auth'), function(){
    Route::get('vehicle', 'VehicleController@VehicleLayout');
    Route::get('foo', 'FooController@BarAction');
});

答案 1 :(得分:0)

在laravel中,按照你的要求行事很简单。

有一个函数可以检查登录表单中的值,然后检查用户是否存在于数据库中。

if (Auth::attempt(array( 'email' => $email, 'password' => $password ) ) )
{

return Redirect::to( 'your route' );     // route for loged users

}else
{

return Redirect::to('/home')->withMessage('Wrong username/pass')

}

在主页上,您可以显示错误消息,如{{If(Session :: has(&#39; message&#39;){{$ message}}}}

如果您在数据库中有该用户,该函数会将您重定向到loged用户去的页面,然后您可以键入Auth :: user() - &gt; username,您将能够访问该数据的任何数据用户。

**要检查用户是否有人,请输入

if(Auth::check){
then do something
}else{
do something else
}**
相关问题