How can i redirect to another route handler inside the closure?
If there is the
$app instance available then like this: http://www.slimframework.com/docs/v4/objects/routing.html#redirect-helper
In all other (default) cases, the $response object should be used:
Within a route closure:
$response = $response->withStatus(302); return $response->withHeader('Location', 'my url');
Within a middleware:
$response = $responseFactory->createResponse(302); return $response->withHeader('Location', 'my url');
Tip 1: Instead of using a fix number, a constant should be used for the http status codes:
// composer require fig/http-message-util \Fig\Http\Message\StatusCodeInterface::STATUS_FOUND;
Tip 2: Instead using a fix url use the RouteContext object and named routes for the url:
use Slim\Routing\RouteContext; // ... $routeParser = RouteContext::fromRequest($request)->getRouteParser(); $url = $routeParser->urlFor('login'); return $this->responseFactory->createResponse() ->withHeader('Location', $url) ->withStatus(302);
Many thanks for answer!
So if i use this
It will redirect to another handler, insted of returning response to a user?
Yes, the response goes back to the user, and the browser redirects to user to the new url resp. another (route) handler.
It is not possible to do it server side only?
Yes, by using the same action handler for two different urls. But then the client (browser) will not be redirected to the real url.
Update: For redirects you can also use the
$app->redirect(...) helper method.
Read more: Redirect helper