The slim/flash component should work with Slim 4. Make sure that the session is started. The problem is that the container definition requires a running session. But there is a trick to make it work in combination with a IoC container.
composer require slim/flash
Add the container definition:
use Slim\Flash\Messages;
// ...
return [
// ...
Messages::class => function () {
// Don't use $_SESSION here, because the session is not started at this moment.
// The middleware changes the storage.
$storage = [];
return new Messages($storage);
},
];
Add a custom Middleware to pass the session storage, e.g. in src/Middleware/SlimFlashMiddleware.php:
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Flash\Messages;
final class SlimFlashMiddleware implements MiddlewareInterface
{
/**
* @var Messages
*/
private $flash;
public function __construct(Messages $flash)
{
$this->flash = $flash;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// Set new flash message storage
$this->flash->__construct($_SESSION);
return $handler->handle($request);
}
}
The session must be started first.
To prevent an error like Fatal error: Uncaught RuntimeException: Flash messages middleware failed. Session not found. add the SessionFlashMiddlewarebefore the SessionMiddleware.
<?php
use App\Middleware\SessionFlashMiddleware;
use App\Middleware\SessionMiddleware;
// ...
$app->add(SessionFlashMiddleware::class); // <--- here
// Start the session
$app->add(SessionMiddleware::class);
Getting Errors like Flash messages middleware failed. Session is not found issue.
Can you share the class detail of SessionFlashMiddleware & SessionMiddleware?
Also, adding SlimFlashMiddleware in the middleware.php file like $app->add(SlimFlashMiddleware::class); is correct?