【问题标题】:Laravel 5: How to add Auth::user()->id through the constructor ?Laravel 5:如何通过构造函数添加 Auth::user()->id ?
【发布时间】:2015-09-08 12:44:03
【问题描述】:

我可以像这样获取经过身份验证的用户的 ID:

Auth::user()->id = $id;

很好用,...但是我有很多需要它的方法,我想要一种更简洁的方法将它作为一个整体添加到类中,所以我可以在每个方法中引用 $id。我正在考虑将其放入构造函数中,但由于 Auth::user 是静态的,所以我把事情弄得一团糟,不知道该怎么做。

非常感谢您的帮助!

【问题讨论】:

    标签: authentication laravel constructor


    【解决方案1】:

    您可以在整个应用程序中使用 Auth::user()。你在哪里并不重要。但是,为了回答您的问题,您可以使用控制器文件夹中的“控制器”类。在那里添加一个构造函数并引用用户 ID。

    <?php namespace App\Http\Controllers;
    
    use Illuminate\Foundation\Bus\DispatchesCommands;
    use Illuminate\Routing\Controller as BaseController;
    use Illuminate\Foundation\Validation\ValidatesRequests;
    
    /* Don't forget to add the reference to Auth */
    use Auth;
    
    abstract class Controller extends BaseController {
    
        use DispatchesCommands, ValidatesRequests;
    
        function __construct() {
            $this->userID = Auth::user()?Auth::user()->id:null;
        }
    }
    

    然后,在任何控制器的任何方法中,您都可以使用 $this->userID 变量。

    【讨论】:

      【解决方案2】:

      您可以注入身份验证类的合​​同,然后在控制器上设置用户 ID,而不是使用外观。就像@rotvulpix 展示的那样,您可以将它放在您的基本控制器上,以便所有子控制器也可以访问用户 ID。

      <?php
      
      namespace App\Http\Controllers;
      
      use Illuminate\Contracts\Auth\Guard;
      
      class FooController extends Controller
      {
          /**
           * The authenticated user ID.
           *
           * @var int
           */
          protected $userId;
      
          /**
           * Construct the controller.
           *
           * @param  \Illuminate\Contracts\Auth\Guard  $auth
           * @return void
           */
          public function __construct(Guard $auth)
          {
              $this->userId = $auth->id();
          }
      }
      

      守卫有一个id() 方法,如果没有用户登录,则返回void,这比通过user()-&gt;id 要容易一些。

      【讨论】:

      【解决方案3】:

      Laravel >= 5.3

      您无法在控制器的构造函数中访问会话或经过身份验证的用户,因为中间件尚未运行。

      作为替代方案,您可以直接在控制器的构造函数中定义基于闭包的中间件。在使用此功能之前,请确保您的应用程序正在运行 Laravel 5.3.4 或更高版本:

      class UserController extends Controller {
      
          protected $userId;
      
          public function __construct() {
      
              $this->middleware(function (Request $request, $next) {
                  if (!\Auth::check()) {
                      return redirect('/login');
                  }
                  $this->userId = \Auth::id(); // you can access user id here
           
                  return $next($request);
              });
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-09
        • 1970-01-01
        • 2020-05-15
        • 1970-01-01
        • 2017-11-10
        • 2019-06-27
        • 2015-01-26
        相关资源
        最近更新 更多