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

eggplantSword's avatar

Store value globally in controller

I need to save a token to then use in all methods of a specific controller, I tried putting it in session but then when I try to use it it says it's null.

This is what I have where I get the token, which does return a token value

session(['access_token' => $res_body->access_token]);

dd(session('access_token'));

But when I try to use session('access_token') in another method it returns null.

What is the best way to achieve this?

0 likes
28 replies
eggplantSword's avatar

@drewdan I'm not sure what you mean by session driver I just wrote session() and used the first one. According to the docs that the global helper.

The value I need to save is a string.

drewdan's avatar

If you go into your .env file and you should see some entries which define which drivers are using in Laravel, there are some for mail, cache etc:

BROADCAST_DRIVER=pusher
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=600

Mine look like this, because I have a redis instance setup locally. Can you show me what your SESSION_DRIVER is?

Snapey's avatar

be aware that session is only saved at the end of the request cycle. If you

session(['access_token' => $res_body->access_token]);

dd(session('access_token'));

then the session is not saved because the dd prevents the request cycle completing and saving the data to session.

1 like
drewdan's avatar

Today I learned! I did not know that!

@msslgomez try doing the dd in the place where you need the data and see if appears then

eggplantSword's avatar

@snapey if I need this value to always be there would session be the correct place to save it? I'll remove that dd.

Snapey's avatar

Yes, save in session if it is specific to this user (since session belongs to user)

eggplantSword's avatar

@drewdan It's still null, I removed the dd after setting the session value but I'm not sure if I need to add a return or something.

Snapey's avatar

do you know if this code is called?

Laravel debugbar will show you whats in session

eggplantSword's avatar

@snapey I don't have that but I did do dd(session()->all()) and it returns an empty array. As far as I understand I only need to get the token once and use it, do session variable go away when someone logs out or after redirects? Maybe it would be better to store it in the .env?

Snapey's avatar

session is per user and is lost if they logout or their session ends

As we dont know what you are trying to share, and why, how can we possibly advise?

eggplantSword's avatar

@snapey I'm trying to use an API for processing credit cart payments and the first step is getting the authorization token, after that every HTTP request must include that token in it to work. The docs for this api a vague all it says is After getting the token it must be sent in every request going forward, I'm assuming that means I only need to get it once. So I need to save it somewhere it won't get removed or lost.

Snapey's avatar

the token will almost certainly expire so you need to consider this

So you need to programatically save a value. Probably easiest is to store in cache with remember forever

Wrap your function that returns the api code in a cache callback

$key = Cache::rememberForever('payment_token', function () {
    return getApiKey();
});
eggplantSword's avatar

@snapey You're right it does say the token expires, this is what gets returned when I get a token

{"access_token": "70LNuFOWoZ", "token_type": "Bearer", "expires_in": 36000, "scope": "read write groups"}

Probably easiest is to store in cache with remember forever. Wrap your function that returns the api code in a cache callback

I'm not following you here. What should I do?

eggplantSword's avatar

@snapey Where would I put that?

Does the 36000 expire time refer to ms, that would mean each token is only good for 36 seconds? If it is than I gravely misunderstood that part.

Snapey's avatar

Does the 36000 expire time refer to ms?

How could I possibly know?

You have some code to get the api key. When you get it, store it in the cache.

In my example, this would be the getApiKey() function. The value it returns is stored in cache, then when you do another api request, it gets it from the cache and not by calling the api again

eggplantSword's avatar

@snapey Like this

public function getToken()
    {
       //get $res_body

        return $res_body->access_token;
    }

public function simpleCharge()
    {
        $key = Cache::rememberForever('payment_token', function () {
            return $this->getToken();
        });

       //use $key 
    }
automica's avatar

@msslgomez session expiry time is stated is in seconds. So your 36000 is 10 hours (60x60x10)

Your session wouldn’t be very much use if it expired in 36 seconds.

eggplantSword's avatar

@automica the 36000 expiry time comes from the API call for the token. I don't know if it's in seconds or ms or what. But yea I think maybe if its 36 seconds then I would need to get a new token every time a want to make a API request. But I'm not sure

Snapey's avatar

10 hours makes sense

Your function to get the key needs to include all the steps. at the moment it just gets a local parameter

eggplantSword's avatar

@snapey Like this?

public function getToken()
    {
       //get $res_body

        $key = Cache::rememberForever('payment_token', function () {
            return $res_body->access_token;
        });

        return $key;
    }

public function simpleCharge()
    {
        $key = Cache::rememberForever('payment_token', function () {
            return $this->getToken();
        });

       //use $key 
    }
Snapey's avatar

no because this

return $res_body->access_token;

does not include all the steps to get a token

eggplantSword's avatar

@snapey Oh I understand, so the method itself would go in that return.

public function getToken()
    {
        $key = Cache::rememberForever('payment_token', function () {
            $client = new Client();

            $params = [
                'client_id' => env('4GEEKS_CLIENT_ID'),
                'client_secret' => env('4GEEKS_CLIENT_SECRET'),
                'grant_type' => 'client_credentials',
            ];

            $headers = [
                'Accept' => 'application/json',
            ];

            $response = $client->request('POST', 'https://api.pay/token/', [
                'json' => $params,
                'headers' => $headers
            ]);

            $res_body = json_decode($response->getBody()->getContents());

            return $res_body->access_token;
        });
        
        return $key;
    }
Snapey's avatar

yes, thats more like it, so to make it work long term you have two options

  • only remember the key for the duration the api states. change rememberForever to remember and then add the cache duration. I would pick maybe 50% of the token lifetime

  • leave the code as it is, then when you get an error from the api where the bearer token is expired, flush it from the cache and the repeat the call

I would probably end up doing both

eggplantSword's avatar

@snapey I'm going to try and figure out what the 36000 actually is time wise, the token I got yesterday right now is returning a 401 so it's expired, so I know probably it's closer to 10 hours than 36 seconds.

So basically I should check the status code if it's a 401 get the token again, and if its a 200 proceed. Should I handle all the status codes separately in like a switch? According to their docs there are 10 status codes that could be returned.

Please or to participate in this conversation.