在 laravel 辅助函数中重定向

redirect in laravel helper function

我在 laravel 助手 class 中创建了函数来检查 app/lib/Auth.php

中的身份验证

class Auto extends \BaseController {

    public static function logged() {
        if(Auth::check()) {
            return true;
        } else {
            $message = array('type'=>'error','message'=>'You must be logged in to view this page!');

            return Redirect::to('login')->with('notification',$message);    
        }
    }
}

在我的控制器中

class DashboardController extends \BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        Auto::logged();
        return View::make('dashboard.index');
    }

我希望它在未登录时重定向到登录路径,但它会加载 dashboard.index 视图并显示消息 'You must be logged in to view this page!'。

如何使用此消息重定向到登录路径?

这应该可行:

 /**
 * Display a listing of the resource.
 *
 * @return Response
 */
public function index()
{
    if(Auto::logged()) {
       return View::make('dashboard.index');
    }
}

为什么要为此创建新的辅助函数。 Laravel 已经为您处理好了。参见 app/filters.php。您将看到如下所示的身份验证过滤器

Route::filter('auth', function()
{
    if (Auth::guest())
    {
        if (Request::ajax())
        {
            return Response::make('Unauthorized', 401);
        }
        else
        {
            return Redirect::guest('/')->with('message', 'Your error message here');
        }
    }
});

您可以确定用户是否已通过身份验证,如下所示

if (Auth::check())
{
    // The user is logged in...
}

Laravel doc 上阅读有关身份验证的更多信息。