Passing Variables between Middleware Classes

What’s the best way to pass variables between middleware classes?

Let’s say I have the following:

Middleware1
— do nothing on way in
Middleware2
— set foo = bar
Middleware2
— do nothing on way out
Middleware1
— get value of foo

Any thoughts and suggestion greatly appreciated!

Thanks!

Middleware passes along the Request object, so adding whatever variables you wish to that is typically how I do it.

$request = $request->withAttribute('foo', 'bar');
$response = $next($request, $response);
1 Like