The Slim Framework support forum has moved to This Tender forum is no longer maintained or monitored.

Get variable from middleware in slim 3

jaklimoff's Avatar


18 Nov, 2015 06:16 AM

Hello. I m totally confused about how i should pass some user data from middleware to route...

I have made my first app and add the authorization middleware to some routes, that validate user cookies, get user data from database. But now, I want to use $user variable in route. How can I solve my problem?

here the code od middleware:

$mw = function ($request, $response, $next) use ($app, $db) {
        $user_id = Dflydev\FigCookies\FigRequestCookies::get($request, 'user_id')->getValue();
        $some_value = Dflydev\FigCookies\FigRequestCookies::get($request, 'some_value')->getValue();
        $user = call_user_func($app->getContainer()->get('get_user_by_id'), $user_id);

        if($user && $some_value == md5($user['user_id'].$user['mail'].$app->getContainer()->get('salt'))) {
            $response->write("user: ".json_encode($user)."<br>");
        } else {
            return $response->withRedirect($app->router->pathFor('login'));
        $response = $next($request, $response);
        return $response;
  1. 1 Posted by Rob Allen on 18 Nov, 2015 08:19 PM

    Rob Allen's Avatar

    Use $request = $request->withAttribute('user', $user); in the middleware and then pick up with $user = $request->getAttribute('user');

  2. 2 Posted by Fernando on 24 Feb, 2016 06:05 PM

    Fernando's Avatar

    How to do that in Slim 2?

  3. 3 Posted by Fernando on 24 Feb, 2016 06:41 PM

    Fernando's Avatar

    I'm sure that there is a better way, but I did that in Slim 2...

    // Append variable to body
    $body = $this->app->request->getBody();
    $a = json_decode($body, true);
    $a['new_var'] = 'something';
    $json = json_encode($a);

    $env = $this->app->environment;
    $env['slim.input'] = $json;

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:


Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts


? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac