After completing the tflight answer, you will need to do the following so that everything works as intended. I tried to present this as a revision, given that the code provided in tflight's answer will not work with the framework out of the box, but it was rejected, therefore, providing it in a separate answer:
You will need the following addition to your middleware:
protected $router; public function __construct($router) { $this->router = $router; }
In addition, when declaring middleware, you need to add the following constructor:
$app->getContainer()->get('router')
Something like:
$app->add(new YourMiddleware($app->getContainer()->get('router')));
Without these changes, the solution will not work, and you will receive an error message that $ this-> router does not exist.
With these changes, you can use the code provided by tflight
$uri = $request->getUri()->withPath($this->router->pathFor('home')); return $response = $response->withRedirect($uri, 403);
source share