Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ziaakbari's avatar

How to initialize a global variable inside one function and access in another function inside controller

Hi there, I know a global variable should be initialized by contractor. what if need to init a global variable inside one function and access it in another function.

this is my first function

	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());
            }
    }

this is my second function

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

I'm creating customer in Stripe and assign created customer id to $customerId global variable, I need $customerId insid paymentDetails function which gets calling by another route, but paymentDetails return null. could anyone help please, how to get customer id in other functions?

0 likes
3 replies
MichalOravec's avatar

Use session for that

public function store(CheckoutRequest $request)
{
    // other code

    $request->session()->put('customerId', $customer->id);

    // other code
}

public function paymentDetails(Request $request)
{
    if ($request->session()->has('customerId')) {
        $customerId = $request->session()->get('customerId');
    }
}

Docs: https://laravel.com/docs/7.x/session

ziaakbari's avatar

Thanks @michaloravec for answering

I tried session, my front is vue n route is defined in api.php, as api is stateless, session is not accessible through api, I'm looking for a solution to store $customerId in the backend for later request.

I found a solution using session, but don't know is it a good practice or not. I defined my route in web.php and call that in vuejs. please give your Ideas if it's not a bad practice I can go ahead?

thanks

Sinnbeck's avatar

Perhaps generate a token that you send in. You can then use that token to look up the customer ID from the database

  1. Send request to the first route. It creates a token and links it to the customer ID in the db. Return the token
  2. Send a request to second route with the token. You can now find the customer ID using the token

Please or to participate in this conversation.