Skip to content
Luca Ubiali Web Developer

Understanding Laravel's Context Capabilities - Using Stacks and Handling Events

September 11th, 2024
Continuous Learning

Episode - https://laracasts.com/series/understanding-laravels-context-capabilities/episodes/6


Context has a way to store arrays (called stacks) through the push method.

1Context::push('queued_jobs', json_encode($this));

When retrieving queue_jobs through get method, the whole array (not a collection!) will be returned.

There’s no method to delete or pop a single item from the stack. In order to do that we have to retrieve the whole array from Context, change it and store it back into Context. After that we can keep using push as normal.

1Context::push('stack', 'item-1');
2Context::push('stack', 'item-2');
3Context::push('stack', 'item-3');
4 
5$array = Context::get('stack'); // ['item-1', 'item-2', 'item-3']
6array_pop($array); // ['item-1', 'item-2']
7 
8Context::add('stack', $array);
9Context::push('stack', 'item-4'); // ['item-1', 'item-2', 'item-4']

Context exposes two events: dehydrating and hydrated. They fire before data is stored in Context and after it was retrieved.

These can be handy central locations to alter how Context works globally. The example provided by Laravel docs and the lesson is to use it to store the user’s locale, so it can be retrieved later when a job will use Context data.

An alternative use case I can think of is: imagine we did go wild with the amount of data stored in Context and now our application is struggling to keep memory usage in check. What we could do is add some logic in the dehydrating event to check Context size and throw an error or write a log if Context size exceeds a certain threshold. This way we’ll be able to identify the main offenders and take action.