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.
@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.
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.
@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.
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
// ...
}
}