【问题标题】:Laravel 5.2 - access authenticated user in route bindingLaravel 5.2 - 在路由绑定中访问经过身份验证的用户
【发布时间】:2016-07-29 22:41:29
【问题描述】:

是否可以在路由绑定中访问经过身份验证的用户。

Route::bind('account', function($account_id)
{
    dd(auth()->user()); // it's null :(

    $account = App\Models\Account::where('business_id', auth()->user()->business_id)
        ->where('account_id', $account_id)
        ->first()

    return !is_null($account) ? $account : App::abort(404);
});

我尝试在一些身份验证中间件中对路由绑定进行分组,没有骰子 - 这是一回事吗?避免在控制器中进行额外验证会非常有用。

帮助表示赞赏。

【问题讨论】:

    标签: php laravel-5


    【解决方案1】:

    只要绑定在 Auth 中间件中,您就应该能够使用 Auth::user() 访问它

    Route::bind('account', function($account_id)
    {
        dd(Auth::user()); // Here is the change
    
        $account = App\Models\Account::where('business_id', Auth::user()->business_id)
            ->where('account_id', $account_id)
            ->first()
    
        return !is_null($account) ? $account : App::abort(404);
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用\Auth。这对我有用:

      RouteServiceProvider:

      public function boot(Router $router) {
      
          parent::boot($router);
      
          $router->bind('account', function () {
              dd(\Auth::user());
          });
      }
      

      routes.php

      Route::get('account/{account}', function () {
          //test
      });
      

      打印用户对象

      【讨论】:

      • 我很遗憾没有意识到您正在使用 RouteServiceProvider。所以我将不得不在引导方法中绑定经过身份验证的用户。
      • 我需要在我的路由文件中绑定 auth 对象的范围。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2020-01-01
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 2016-09-15
      相关资源
      最近更新 更多