You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel控制器构造函数中Auth::user()返回null的解决方法

问题根因

Laravel 框架的控制器构造函数执行时机早于会话、身份认证等路由中间件的初始化流程,Auth::user()依赖的身份校验逻辑还没有运行,因此在构造函数中调用必然返回 null,属于框架正常的设计逻辑,并非代码编写错误。

实现方案

将 DataService 初始化逻辑封装为独立方法,在业务方法执行时调用即可,此时身份认证中间件已经运行完成,Auth::user()可以正常获取到认证用户数据。
还可以进一步优化代码,避免重复初始化实例、减少冗余代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use QuickBooksOnline\API\Facades\Invoice;
use QuickBooksOnline\API\DataService\DataService;

class QuickBooksAPIController extends Controller
{
    // 缓存初始化后的DataService实例
    protected ?DataService $dataService = null;

    public function dataService(): DataService
    {
        if (is_null($this->dataService)) {
            $this->dataService = DataService::Configure([
                'auth_mode'       => 'oauth2',
                'ClientID'        => config('services.quickbooks.client_id'),
                'ClientSecret'    => config('services.quickbooks.client_secret'),
                'accessTokenKey'  => Auth::user()->access_token_key,
                'refreshTokenKey' => Auth::user()->access_token_secret,
                'QBORealmID'      => Auth::user()->target_realm,
                'baseUrl'         => 'Development'
            ]);
            // 通用配置统一设置,无需每个业务方法重复编写
            $this->dataService->setLogLocation(storage_path('logs/quickbooks.log'));
            $this->dataService->throwExceptionOnError(true);
        }
        return $this->dataService;
    }

    public function getInfo()
    {
        $companyData = $this->dataService()->getCompanyInfo();
        return response(['company' => $companyData], 200);
    }

    public function batchInvoices()
    {
        $batch = $this->CreateNewBatch();
        $invoices = \App\Models\Invoice::all()->take(30);

        foreach ($invoices as $invoice) {
            $newInvoice = Invoice::create([
                "Line" => [
                    [
                        "Amount" => $invoice->amount,
                        "DetailType" => "SalesItemLineDetail",
                        "SalesItemLineDetail" => [
                            "ItemRef" => [
                                "value" => 1,
                                "name" => "Services"
                            ]
                        ]
                    ]
                ],
                "CustomerRef" => [
                    "value" => 1
                ]
            ]);
            $batch->AddEntity($newInvoice, $invoice->invoice_number, "Create");
        }

        $batch->Execute();
        $error = $batch->getLastError();
        if ($error) {
            return response(['error' => $error], 500);
        }
    }

    public function getAllByCategory(Request $request, $category)
    {
        $allOfCategory = $this->dataService()->Query("SELECT * FROM " . $category, $request->currentPage, $request->perPage);
        $countOfCategory = $this->dataService()->Query("SELECT COUNT(*) FROM " . $category);
        return response([$category => $allOfCategory, "count" => $countOfCategory], 200);
    }

    public function batchDelete(Request $request)
    {
        logs($request);
    }
}
注意事项
  • 该控制器的所有路由必须绑定auth中间件,保证访问接口的用户已经完成身份认证,避免Auth::user()返回null导致报错
  • 建议将QuickBooks相关配置添加到config/services.php配置文件中,使用config()函数读取配置,不要直接使用env()函数,避免 Laravel 生成配置缓存后env()函数返回空值的问题

内容的提问来源于stack exchange,提问作者Riza Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 11:33:00