# Passing Variables between Middleware Classes

**URL:** <https://discourse.slimframework.com/t/passing-variables-between-middleware-classes/854>\
**Category:** Questions\
**Created:** [October 28, 2016, 4:34pm UTC](https://discourse.slimframework.com/t/passing-variables-between-middleware-classes/854 "2016-10-28T16:34:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kmlong1183](https://avatars.discourse-cdn.com/v4/letter/k/8dc957/32.png) [@kmlong1183](https://discourse.slimframework.com/u/kmlong1183)\
**Post date:** [October 28, 2016, 4:34pm UTC](https://discourse.slimframework.com/t/passing-variables-between-middleware-classes/854/1 "2016-10-28T16:34:03Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![tflight](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/tflight/32/1205_2.png) [@tflight](https://discourse.slimframework.com/u/tflight)\
**Post date:** [October 28, 2016, 4:54pm UTC](https://discourse.slimframework.com/t/passing-variables-between-middleware-classes/854/2 "2016-10-28T16:54:05Z")

</div>

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

```php
$request = $request->withAttribute('foo', 'bar');
$response = $next($request, $response);

```
