Laravel 5:如何通过构造函数添加 Auth::user()->id ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30990556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:49:22  来源:igfitidea点击:

Laravel 5: How to add Auth::user()->id through the constructor ?

authenticationlaravelconstructor

提问by Vince

I can get the ID of the authenticated user like this:

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

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

Great it works, ... but I have a load of methods which need it and I want a cleaner way of adding it to the class as a whole,so I can just reference the $id in each method. I was thinking of putting it into the constructor, but as Auth::user is a static, I am making a mess of things and don't know how to do it.

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

Many thanks for your help !

非常感谢您的帮助 !

采纳答案by rotvulpix

You can use Auth::user() in the whole application. It doesn't matter where you are. But, in response to your question, you can use the 'Controller' class present in your controllers folder. Add a constructor there and make the reference to the user ID.

您可以在整个应用程序中使用 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;
    }
}

Then, in any method of any controller you can use the $this->userID variable.

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

回答by Dwight

Instead of using the Facade you can inject the contract for the authentication class and then set the user ID on your controller. Like @rotvulpix showed you could put this on your base controller so that all child controllers have access to the user ID too.

您可以为身份验证类注入合约,然后在控制器上设置用户 ID,而不是使用 Facade。就像@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();
    }
}

The guard has an id()method which returns voidif no user is logged in, which is a little easier than having to go through user()->id.

守卫有一个id()方法,它void在没有用户登录时返回,这比必须通过 更容易一些user()->id

回答by Ali Sherafat

Laravel >= 5.3

Laravel >= 5.3

you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.

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

As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4or above:

作为替代方案,您可以直接在控制器的构造函数中定义基于闭包的中间件。在使用此功能之前,请确保您的应用程序正在运行 Laravel5.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);
        });
    }
}