【问题标题】:How to initialize a global variable inside one function and access in another function inside Laravel controller如何在一个函数中初始化全局变量并在 Laravel 控制器中访问另一个函数
【发布时间】:2020-08-11 11:33:53
【问题描述】:

我知道一个全局变量应该由承包商初始化。如果需要在一个函数中初始化一个全局变量并在另一个函数中访问它。

这是我的第一个功能

    public $customerId;

    public function store(CheckoutRequest $request)
    {
        try {
            $customer = Stripe::customers()->create([
                                'source' => $request->stripeToken,
                                'email' => $request->email,
                                'description' => $request->name
                            ]);

            **$this->customerId** = $customer->id;
            $this->chargeCustomer($request, $customer->id);
            return redirect()->route('shipper.payment')->with('success_message', 'Thank you! your payment was successfull.');
        } catch (Exception $e) {
            return back()->withErrors('Error! ' . $e->getMessage());
        }
    }

这是我的第二个功能

    public function paymentDetails()
    {
        return $this->customerId;
    }

我在 Stripe 中创建客户并将创建的客户 ID 分配给 $customerId 全局变量,我需要 $customerId 在 paymentDetails 函数中,该函数被另一条路由调用,但 paymentDetails 返回 null。谁能帮忙,如何在其他功能中获取客户ID?

【问题讨论】:

    标签: php laravel cartalyst


    【解决方案1】:

    如果您,正如您所描述的,稍后通过另一条路线调用paymentDetails(),则将不再设置公共变量。控制器根据请求进行解析,因此它不会为下一个请求存储任何内容。

    您最好的选择可能是在您自己的一端存储一些客户,并在下一个请求时使用它来检索 customerId,或者使用https://laravel.com/docs/7.x/session

    【讨论】:

    • 我尝试了会话,我的前面是 vue n 路由是在 api.php 中定义的,因为 api 是无状态会话在那里无法访问,我正在寻找一种解决方案来在后端存储 $customerId稍后请求。还有其他方法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 2012-12-16
    • 1970-01-01
    • 2023-03-20
    • 2022-12-06
    • 1970-01-01
    相关资源
    最近更新 更多