【问题标题】:redirect in laravel helper function在 laravel 辅助函数中重定向
【发布时间】:2015-01-12 09:15:02
【问题描述】:

我在 laravel 帮助类中创建了函数来检查 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 视图并显示消息“您必须登录才能查看此页面!”。

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

【问题讨论】:

  • 你意识到 Laravel 已经有一个 Auth 类,功能和你的一样吗? Documentation
  • 我建议使用路由过滤器来锁定登录用户的区域。看看他们的文档:laravel.com/docs/4.2/routing#route-filters
  • 如果没有记录,我想在一个函数中检查身份验证并重定向到登录页面,因此我可以在每个函数中只使用一个检查身份验证的函数实例并发送相同的消息。

标签: php laravel


【解决方案1】:

为什么要为此创建新的辅助函数。 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 上阅读有关身份验证的更多信息。

【讨论】:

    【解决方案2】:

    这应该可行:

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

    【讨论】:

      猜你喜欢
      • 2022-08-04
      • 2019-12-29
      • 1970-01-01
      • 2016-01-06
      • 2018-05-07
      • 2015-04-02
      • 2015-04-13
      • 2014-04-19
      • 1970-01-01
      相关资源
      最近更新 更多