There are three common responses that you’ll return from your controller methods or route Closures: views, redirects, and errors. We’ve already covered views and we’ll cover errors next, but let’s address redirects.

There are two common ways to generate a redirect; we’ll use the Façades here, but you may prefer the global helper. Both are create an instance of Illuminate\Http\RedirectResponse, performing some convenience methods on it, and then returning it; you could do this manually, but you’ll have to do a little more work yourself.

Three ways to return a redirect

 Route::get('redirect-with-facade', function () { return Redirect::to('auth/login'); }); Route::get('redirect-with-helper', function () { return redirect()->to('auth/login'); }); Route::get('redirect-with-helper-shortcut', function () { return redirect('auth/login'); }); ,

Note that the redirect() helper exposes the same methods as the Redirect Façade, but it also has a shortcut; if you pass parameters directly to the helper, instead of chaining methods after it, it’s a shortcut to the to() Redirect method.

You’ll notice to(), the most commonly used redirect method, has a first parameter that should be set to the URI that you want to redirect the user to. There are a few other options available, though.

Redirect to

The method signature for the to() method for redirects looks like this:

function to($to = null, $status = 302, $headers = [], $secure = null)

$to is a valid internal URI; $status is the HTTP status (defaulting to 301 FOUND); $headers allows you to define which HTTP headers to send along with your redirect; and $secure allows you to override the default choice of http vs https (which is normally set based on your current request URL).

Advertisements