Hey all. Today’s post is a response to a question asked today on IRC.

The question:

In zf1 within a controller I could do something like $this->getResponse()->setRedirect(‘/foo/bar’, 201) ~ How do I do that using zf2?

The answer:

Controllers have plugins, not much has changed there. Except for the fact that it’s now even easier to get a redirect going. Check this out:

$this->redirect()->toRoute('routeName');

It also has a toUrl method, which behaves the same way:

$this->redirect()->toUrl('http://google.nl/');

Counter question:

Can you send a statusCode with that though?

Counter answer:

Yes, you can. As seen here, the redirect returns a Response. A response has a setStatus code, thus allowing us to do this:

$this->redirect()->toRoute('routeName')->setStatusCode(201);

Happy coding 🙂