Search code examples
phpslimslim-3

How to redirect and store data for the request after the redirect


I am trying to redirect the user to the login page with errors and a flash message.

Currently I'm doing this:

return $this->container->view->render($response,'admin/partials/login.twig',['errorss'=>$errors]);

But I want to redirect to the login page, while still having the errror messages and the flash message. I tried this way but does not work:

$this->container->flash->addMessage('fail',"Please preview the errors and login again."); 
return $response->withRedirect($this->container->router->pathFor('admin.login',['errors'=>$errors]));

Solution

  • You've already used slim/flash, but then you did this:

    return $response->withRedirect($this->container->router->pathFor('admin.login',['errors'=>$errors]));
    

    which is not correct. The second parameter on the Router#pathFor() method is not for data to use after the redirect

    The router’s pathFor() method accepts two arguments:

    1. The route name
    2. Associative array of route pattern placeholders and replacement values

    Source (http://www.slimframework.com/docs/objects/router.html)

    So you can set placeholders like profile/{name} with the second parameter.

    Now you need to add your errors all together to the slim/flash`.

    I'm expaining this on the modified Usage Guide of slim/flash

    // can be 'get', 'post' or any other method
    $app->get('/foo', function ($req, $res, $args) {
        // do something to get errors
        $errors = ['first error', 'second error'];
    
        // store messages for next request
        foreach($errors as $error) {
            $this->flash->addMessage('error', $error);
        }
    
        // Redirect
        return $res->withStatus(302)->withHeader('Location', $this->router->pathFor('bar'));
    });
    
    $app->get('/bar', function ($request, $response, $args) {
        // Get flash messages from previous request
        $errors = $this->flash->getMessage('error');
    
        // $errors is now ['first error', 'second error']
    
        // render view
        $this->view->render($response, 'admin/partials/login.twig', ['errors' => $errors]);
    })->setName('bar');