Redirects in Laravel 5.4

There are two common ways to generate a redirect; we’ll use the Façades here, but you may prefer the global helper. Both 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.

Redirect with facade

Route::get('redirect', function () {
       return Redirect::to('auth/login');

Redirect with helper

Route::get('redirect', function () {
       return redirect()->to('auth/login');

Redirect with helper shortcut

Route::get('redirect', function () {
       return redirect('auth/login');

When a user visits a page they’re currently not authenticated for—for example, visiting a dashboard when their login session has expired—Laravel captures their intended URI and redirects back to it after a successful authentication. This is performed using guest() and intended()Redirect::guest() is a normal Redirect::to() redirect, except it captures the current URL in a query parameter named “url.intended” for use later. You would use this to redirect a user away from their current URL with the intent for them to return after authentication.

Redirect::intendend() grabs the url.intended query parameter and redirects to it. You would use this after successfully authenticating a user, to redirect them back to their intended URI. Thankfully, the baked-in Laravel authentication already handles these both for you, but you can use them manually if you’re doing your own authentication.

Other redirect methods

  • home() redirects to a route named home.
  • refresh() redirects to the same page the user is currently on.
  • away() allows for redirecting to an external URL without the default URL validation.
  • secure() is like to() with the secure parameter set to true.
  • action() allows you to send to a controller and method like this: action(MyController@method).

You can pass along either an array of keys and values or a single key and value using with(), like in the following examples.

Redirect with key values

Route::get('redirect', function () {
    return Redirect::to('dashboard')->with('error', true);

Redirect with Array

Route::get('redirect', function () {
    return Redirect::to('dashboard')->with(['error' => true, 'message' => 'Whoops!']);


Popular posts from this blog

Fatal: LoadModule: error loading module 'mod_sql_mysql.c'

Regular Expression Route Constraints And Route Names in Laravel 5.4