Middleware get request attributes after route


I’m trying to use $request->getAttribute(‘title’) in middleware called after a route has returned a response. The route is assigning the title via $request->withAttribute(‘title’,‘Page Title’).


    $app = new Slim\App($appContainer);

	$app->get('/',function($request,$response) {
		$request = $request->withAttribute('title','Home page');
		return $response;

	$mw = function($request,$response,$next) {
		$response = $next($request,$response);
		$title = $request->getAttribute('title');
		$response->write('Title: ' . $title);
		return $response;	


Is it even possible to assign data like this from a route request to middleware?


Have you looked at setArgument?


use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Slim\App as Slim;

require dirname(__DIR__) . '/../vendor/autoload.php';

$config['displayErrorDetails'] = true;
$config['determineRouteBeforeAppMiddleware'] = true;

$app = new Slim(['settings' => $config]);

$app->get('/', function($request, $response) {
    return $response;
})->setArgument('title', 'Home page');

$mw = function($request, $response, $next) {
    $response = $next($request, $response);

    $route = $request->getAttribute('route');
    $title = $route->getArgument('title');

    $response->write('Title: ' . $title);
    return $response;




That does work, however, I was looking for something that I wouldn’t have to add to each route. I ended creating a class to inject into my controllers. After thinking about it, what I wanted to do didn’t really make sense to put that type of responsibility on the request.


The request is not passed back up the chain you need so use something that has state. The most obvious choice is the route object’s arguments. Alternatively, you could use a custom header on the response that you then remove, or you could implement a custom Response object with an attributes property.