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

vincent15000's avatar

Session vs Context

Hello,

I have still difficulty to understand the real difference between a Session and a Context.

A Context seems to work exactly like a Session.

Can somebody explain me ?

Thanks a lot ;).

V

0 likes
7 replies
tykus's avatar

There is a lot more information in the pull request that added the feature, and the discussion that follows.

It is mostly intended for additional logging information, but, because it can cross logical boundaries, you also get to automatically share Context with background jobs which would not have access to the Session.

1 like
jlrdw's avatar

@vincent15000 Authentication uses session, permissions are normally looked up or sometimes cached. I suggest keep using these things as always. But just my opinion.

I prefer to lookup each time whether a user can or cannot do something.

1 like
vincent15000's avatar

@jlrdw For example I think that the Spatie package for permissions uses the cache.

1 like
John Subut's avatar
Level 11

The main difference is persistence: Sessions persist across multiple requests for a user, while Context is request-scoped and only lives for a single request. Consider Session as long-term storage and Context as temporary, request-specific data sharing.

2 likes
vincent15000's avatar

@John Subut Thank you ... hmmm ... I can't imagine any situation where I could use a context, even after reading and re-reading the Laravel documentation.

Can you give some concrete examples please ?

1 like
John Subut's avatar

@vincent15000, you're welcome!

Certainly!

use Illuminate\Support\Facades\Context;

// Set the user's preferred language
Context::put('user_language', 'en');

// Retrieve the user's preferred language in a subsequent request
$language = Context::get('user_language');

Dispatching the Job:

use App\Jobs\ProcessOrderJob;
use Illuminate\Support\Facades\Context;

// Set a context value
Context::set('userId', 123);

// Dispatch the job
ProcessOrderJob::dispatch(456);

Job Class:

namespace App\Jobs;

use Illuminate\Support\Facades\Context;

class ProcessOrderJob implements ShouldQueue
{
    public function __construct(public $orderId) {}

    public function handle()
    {
        // Retrieve the userId from the context (set earlier)
        $userId = Context::get('userId');
        logger("Processing order {$this->orderId} for user {$userId}");
        
        // Process the order
        // ...
    }
}

Please or to participate in this conversation.