Skip to content
Luca Ubiali Web Developer

Understanding Laravel's Context Capabilities - Loading Contextual Data

September 5th, 2024
Continuous Learning

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


Context exists only for a single request life-cycle. This allows Context to be stored in memory which grants better performances than Session that must be stored in some other data store.

A good place to use Context is inside a middleware. This will prevent using Context on all controller and methods that are interested in a specific piece of data.

1namespace App\Http\Middleware;
2 
3 
4class AddContext
5{
6 /**
7 * Handle an incoming request.
8 *
9 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
10 */
11 public function handle(Request $request, Closure $next): Response
12 {
13 Context::add([
14 'active_account' => session('active_account'),
15 'user' => Auth::user(),
16 ]);
17 
18 return $next($request);
19 }
20}

The assumption is that active_account and user will be used frequently across the application and having them in memory and available on all routes that use that middleware, will make consuming the data efficient from both performance and dev experience point of view.

The suggestion is to not go wild with Context data. It would be easy to fill up the memory if too much data is stored there.

I still have to use Context on a real project, but I think I’ll follow the pattern of storing data in middleware only as much as possible. I can already see scenarios where some Context data is used in a view and will be difficult to find where the data is set. If I know Context is only set in middleware at least I’ll have a narrower list of classes to inspect.