An Introduction to Context in Laravel

Darrin Deal -

The Laravel team released today a Context API that is available throughout the lifecycle of a request. The example given in the docs provides insight in how this new API is built into logging functionality but it can be used for so much more. Let’s look at how the API can be used.

Accessing the Context API

Like most Laravel API’s we can access it through the Context facade. This is a key-value storage that only lives for the lifecycle of your request. We are able to add and remove data within a single request. When we then send items to our log so does the context, but it doesn’t have to as we will soon find out. Let’s look at how we can use this API to our advantage.

Let’s say your application allows users to load the application from a custom domain using a service like Caddy or Approximated. In your application you have a middleware where you are loading a tenant’s content.

Add

In this imaginary middleware we can use the following to add out tenant id to the context.

Context::add('tenant_id', $tenant->id);

Now that we have the tenant in the Context of the request we can then use this down the line.

Somethings to note here. If you call this after the first call the content will be overwritten. You can get around this by using the addIf function. You are also able to add multiple items at once by passing in an associative array like so.

Conext::add([
	'tenant_id' => $tenant->id,
	'team_id' => $tenent->team->id
]); 

Get

With what we know this data was added to the context and will now be added to any logs that we send. You can also retrieve that content and use it in our application. You can run the following to get an item for a key.

$tenantID = Context::get('tenant_id');

You can also get multiple individual data for keys by using the following

$data = Context::only(['tenant_id', 'team_id']);

You can get all the data by using the all method.

$data = Context::all();

Remove

Now lets say for whatever reason you need remove an item from the context. In our example you need to remove the team ID mid request you can remove this data like this.

Context::forget('team_id');

And there it is gone.

Other Aspects of the Context API

There are some other features that move this beyond saving day to logs. Let’s look at the has, stacks, andhidden methods as well as the events that are fired by the Context API.

Has

The has method allows to determine if context was set. Let’s say we want to see if the tenant has a team. We can do that with the following.

Context::has('team_id');

One thing to note here if the value of team_id is null but still in the context it will return true regardless of if the value is true or false.

Stacks

My favorite feature of the Context API are stacks. Stacks allow you to add multiple values to one key. Let’s say that your tenant had multiple teams. You can use the following to add each team to one key.

Context::push('teams', 1,4,5,7);

Now when we go to get the teams we will get an array of [1,4,5,7] . I think this so powerful and the example they give in the docs are breadcrumbs. Look out for an article building a view component that uses stacks to build breadcrumbs in the next week or two.

Hidden

If you want to add items to Context but want them to not be added to the logs you can use the hidden version of each method. Here are a list of those.

Context::addHidden(/* ... */);
Context::addHiddenIf(/* ... */);
Context::pushHidden(/* ... */);
Context::getHidden(/* ... */);
Context::onlyHidden(/* ... */);
Context::allHidden(/* ... */);
Context::hasHidden(/* ... */);
Context::forgetHidden(/* ... */);

Events

There are two events that can be used when context is Hydrated and Dehydrated. This is useful when jobs are firing in a queue. When a job is called you can pass in context. These events are used to bring that data in to the current context. In our example we could use this to pass our tenant to the job.

Where to Go From Here?

This is an overview of the new Context API that was released today. How do you think you will use this in your apps. Let me know on X!

Be sure to check back on Friday when I release our first full length tutorial, Getting Started with Laravel Reverb!

Other articles you might enjoy...