【问题标题】:Issue accessing Auth() object data in Laravel class在 Laravel 类中访问 Auth() 对象数据的问题
【发布时间】:2017-08-23 13:07:52
【问题描述】:

我看到了一些行为。通过 Laravel 类中的 Auth 外观访问用户数据时,我无法解释。这是我的代码的摘录:

private $data;
private $userID;//Set property

function __construct()
{
    $this->middleware('auth');//Call middleware
    $this->userID = Auth::id();//Define property as user ID
}

public function index() {
    return view('');
}

public function MyTestMethod() {

    echo $this->userID;//This returns null
    echo Auth::id();//This works & returns the current user ID

}

我已登录并已将 use Illuminate\Support\Facades\Auth; 包含在类中,因此代码有效,但仅在方法中访问 Auth 时 - 否则它返回 null 值。

最奇怪的是,我无法弄清楚是什么原因造成的。任何想法都像以往一样受到赞赏。提前致谢!

【问题讨论】:

  • 现在,升级到 Laravel 5.3 后,Auth::user() 在从控制器的构造函数调用时返回 null。检查这个:laracasts.com/discuss/channels/laravel/…
  • 哇,这里的回复速度太棒了!谢谢大家..让我阅读并尝试建议的代码。

标签: php laravel frameworks


【解决方案1】:

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

作为替代方案,您可以直接在控制器的构造函数中定义基于闭包的中间件。:

试试这个:

function __construct()
{    
    $this->middleware(function ($request, $next) {
       if (!auth()->check()) {
          return redirect('/login');
       }

       $this->userID = auth()->id(); // or auth()->user()->id

        return $next($request);
    });
}

另一个替代解决方案是你的基本控制器类并添加__get 函数,如下所示:

class Controller
{
    public function __get(string $name)
    {
        if($name === 'user'){
            return Auth::user();
        }

        return null;
    }
}

现在,如果您当前的控制器可以像这样使用它$this->user:

class YourController extends Controller 
{
    public function MyTestMethod() {
        echo $this->user;
    }
}

【讨论】:

  • 您好,感谢您的帮助 - 恐怕建议的解决方案都不起作用。我使用的是 5.4.32 版本,所以这就是原因。也尝试过:' public function MyMethod(Request $request) { $userID = $request->user(); echo $userID; } 但不起作用,并且在方法中失败了。我收到类型错误:传递给 App\Http\Controllers\RecommendingService::RecommendByPersonal() 的参数 1 必须是 Illuminate\Http\Request 的实例,没有给出
  • MyMethod() { $userID = request()->user();回显$用户ID; }
  • 感谢 younes 这行得通 - 为语法错误道歉,我认为它需要方法参数。这仍然需要在方法中重复,因此无法实现您通过构造函数建议的内容。任何想法为什么这对我来说失败了?
  • 你试过了吗:` $this->userID = auth()->id(); // 或者 auth()->user()->id`
  • 是的,都按照建议尝试了:private $data; private $userID; function __construct() { $this->middleware(function ($request, $next) { if (!auth()->check()) { return redirect('/login'); } //$this->userID = auth()->id(); $this->userID = auth()->user()->id; return $next($request); }); } 通过 $this->userID 调用并使用使用 Illuminate\Support\Facades\Auth;
【解决方案2】:

你应该试试这个:

function __construct() {
   $this->userID = Auth::user()?Auth::user()->id:null;
}

OR

public function __construct()
{
     $this->middleware(function ($request, $next) {
         $this->userID = Auth::user()->id;
         return $next($request);
     });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 2020-09-20
    • 2019-12-01
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多