MasterPHP.in
Try Compiler →
Laravel Tutorial

Laravel Redirects and Flash Session Data


A user fills in the new invoice form and clicks Save. Your store() method saves the invoice and returns a page that says “Invoice created”. The user is happy, until they press the browser’s refresh button. The browser asks, “Do you want to send the form data again?” The user clicks yes, and now there are two identical invoices.

This is one of the oldest problems in web development, and the fix is simple. After saving something, you should not show a page. You should send the user to a different page, and show a short message there, like “Invoice created successfully”. The message should appear once and then disappear.

In this lesson you will learn how redirects work in Laravel, and how flash session data lets you show one-time messages after a redirect.

 

The Problem with Showing a Page After a Form

When a form is submitted, the browser sends a POST request. If your answer is a normal page, the browser remembers that the current page came from a POST. Refreshing it repeats the whole request, including the data.

Browser  --POST /invoices-->  store() saves invoice, returns a page
Browser  (user presses refresh)
Browser  --POST /invoices-->  store() saves the invoice AGAIN

The same thing happens with a payment form, a contact form or a registration form. A duplicate invoice is annoying, but a duplicate order or payment is a real problem for your customer.

 

What Is a Redirect?

A redirect is a response that does not contain a page. It only says, “Go to this other address”. The status code is usually 302, and the new address is sent in a header called Location. The browser reads it and immediately makes a new GET request to that address.

HTTP/1.1 302 Found
Location: http://localhost:8000/invoices

The user never sees the redirect. They only see the final page. In the last lesson you learned that every controller method ends by returning a response, and a redirect is simply another kind of response.

 

Creating Redirects

The redirect() helper builds a redirect response. You always need to return it, because the redirect only happens when Laravel receives it as the final answer.

 

Redirecting to a Path

You can give the helper a plain path:

return redirect('/invoices');

This works, but it brings back the problem of hardcoded URLs that you solved in the Named Routes lesson. If the URL changes, every redirect breaks silently.

 

Redirecting to a Named Route

The better way is to redirect by route name. Pass the name, and the parameters in an array, exactly as you do with route():

return redirect()->route('invoices.index');

return redirect()->route('invoices.show', ['invoice' => 1001]);

// Shorter helper with the same result
return to_route('invoices.show', ['invoice' => 1001]);

If the URL ever changes, the redirect follows automatically, because Laravel looks up the address from the name.

 

Going Back to the Previous Page

When something goes wrong, you often want to send the user back to where they came from. The back() helper does this:

return back();

Laravel reads the address of the previous page from the request, and sends the user there. If it cannot find one, for example when someone opens the address directly, the user is sent to the home page. This is most useful with forms, because you can send the user back to the form together with their input and error messages. You will build that in the Forms & Validation chapter.

 

Redirecting to Another Website

Sometimes you must send the user outside your app, for example to a Razorpay hosted payment page. Use away() for any address that is not part of your own app:

return redirect()->away('https://razorpay.com/');

The away() method sends the user to the address exactly as it is, without trying to match it to anything inside your project.

 

Changing the Status Code

The default redirect code is 302, which means “temporarily moved”. If a page has moved forever, use 301, so that search engines update their records:

return redirect('/billing/invoices', 301);

You do not need to think about this for normal form handling, where the default is correct. You already met route-level redirects, with Route::redirect(), in the Redirect, View & Fallback Routes lesson. In this lesson, we redirect from inside a controller.

 

The Post/Redirect/Get Pattern

The fix for the duplicate invoice is a pattern with a memorable name: Post, Redirect, Get. After a POST request does its work, never show a page. Redirect to a GET address instead:

Browser  --POST /invoices-->  store() saves the invoice
         <--302 Location: /invoices--
Browser  --GET /invoices-->   index() shows the list

Now the page the user is looking at came from a GET. If they refresh, the browser just asks for the list again, and no second invoice is created. Here is the pattern applied to three methods of InvoiceController:

public function store(Request $request)
{
    $invoice = $this->invoiceService->create(
        $request->input('client'),
        $request->integer('amount'),
    );

    return redirect()
        ->route('invoices.index')
        ->with('status', "Invoice {$invoice['invoice']} created");
}

public function update(Request $request, int $invoice)
{
    // Later: save the changes

    return redirect()
        ->route('invoices.show', ['invoice' => $invoice])
        ->with('status', 'Invoice updated');
}

public function destroy(int $invoice)
{
    // Later: delete the invoice

    return redirect()
        ->route('invoices.index')
        ->with('status', 'Invoice deleted');
}

In the lesson on Responses we returned JSON from store(), because we were talking to a mobile app. A web form needs a redirect instead. A JSON API and a web page behave differently, and you will see how to build proper API controllers later.

 

Flash Session Data

Look at the ->with('status', ...) part of the redirects above. This stores a short message to be shown on the next page. It is called flash data, because it appears once, like a flash, and then it is gone.

Laravel stores the message in the session, which is a small piece of storage that remembers a visitor between requests. You will study sessions properly in the next lesson. For now you only need to know that flash data is placed in the session for exactly one more request, and then removed.

Request 1:  store() saves the invoice
            and flashes  status = "Invoice created"
            --> redirect

Request 2:  index() runs, and the message is available
            --> the page shows it

Request 3:  user refreshes, and the message is gone

 

Showing a Flash Message

You can read the message with the session() helper. In a controller it looks like this:

$message = session('status');

Most often you show it in a view. Blade, which you will study in the next chapters, has a simple @if for this. Here is a basic version you could place at the top of a page:

@if (session('status'))
    <div class="alert">
        {{ session('status') }}
    </div>
@endif

The block appears only when a message exists. After the next request, it will not be there, so the alert disappears by itself. In the Building a Reusable UI Kit lesson, you will turn this into a proper reusable alert component.

 

Trying It Yourself

You cannot submit a real form yet, but you can still see flash data working. Temporarily add a line to index() so that it returns the flash message:

'flash' => session('status'),

Then add a small test route that redirects with a message:

Route::get('/demo/flash', function () {
    return redirect()
        ->route('invoices.index')
        ->with('status', 'Hello from flash data');
});

Visit /demo/flash. You will be redirected to /invoices, and the JSON will show "flash": "Hello from flash data". Refresh the page and the value becomes null. Remove the test route when you are done.

 

Different Kinds of Messages

The key name, status, is your choice. Many projects use separate keys for different kinds of messages, so a view can style them differently:

return back()->with('success', 'Payment received');
return back()->with('error', 'Payment failed. Please try again.');

You can also flash an array, for example a list of items that were skipped during an import.

 

Keeping Flash Data for One More Request

Sometimes flash data disappears before you can show it, for example when one redirect leads to another. You can ask Laravel to keep it alive for one more request:

session()->reflash();                   // keep everything
session()->keep(['status']);            // keep only the status

Use these rarely. If you need them often, the redirect chain is probably too long.

 

Redirecting with Input and Errors

When a form has a mistake, you will redirect back with two extra things: the values the user typed, and the error messages. Laravel has methods for both:

return back()->withInput();
return back()->withErrors(['amount' => 'Amount must be more than zero']);

Both work on the same flash mechanism you just learned. How to show the old values and errors inside a form is covered in the Displaying Errors & Old Input lesson.

 

Common Mistakes

Mistake 1: Forgetting to Return the Redirect

public function destroy(int $invoice)
{
    redirect()->route('invoices.index')->with('status', 'Invoice deleted');
}

Nothing is returned, so no redirect happens, and the browser shows a blank page. There is no error message. Always write return in front of a redirect.

 

Mistake 2: Redirecting to a Route That Does Not Exist

return redirect()->route('invoice.index');

A misspelled route name throws the same error you met in the Named Routes lesson:

Symfony\Component\Routing\Exception\RouteNotFoundException: Route [invoice.index] not defined.

Check the name against php artisan route:list.

 

Mistake 3: Showing a Page Instead of Redirecting After a POST

public function store(Request $request)
{
    // save the invoice
    return view('invoices.created');
}

No error appears, but pressing refresh creates a duplicate record. After saving, updating or deleting, always redirect.

 

Mistake 4: Expecting Flash Data to Stay

Flash data is available for one request only. If the user refreshes, or if you redirect twice in a row, the message is gone. This is not a bug. If you need a message to survive, use reflash() or keep(), or show it on the first page that loads after the redirect.

 

Mistake 5: Using Flash Data on an API Route

Flash data relies on the session, and routes in routes/api.php do not use sessions. If you flash a message in an API route, it will never arrive on the next request. APIs return their messages inside the JSON response instead.

 

Mistake 6: Redirecting to an Address from User Input

return redirect($request->input('next'));

An attacker can send someone a link like ?next=https://fake-bank.example and your own site will send the visitor to it. This is called an open redirect, and it is used in phishing. Redirect only to route names or paths you wrote yourself.

 

Quick Summary

  • A redirect is a response that tells the browser to go to a different address, usually with status 302.
  • Always return the redirect, or nothing happens.
  • Use redirect()->route('invoices.index') or to_route() instead of hardcoded paths.
  • Use back() to return to the previous page, and redirect()->away() for other websites.
  • Use status 301 only when a page has moved permanently.
  • After a POST, PUT or DELETE, redirect to a GET page. This is the Post/Redirect/Get pattern, and it prevents duplicate submissions.
  • Flash data is stored in the session for exactly one more request. Add it with ->with('status', 'Invoice created').
  • Read it with session('status'), and show it in a view with @if.
  • Use reflash() or keep() only if flash data must survive another request.
  • withInput() and withErrors() use the same flash mechanism, and are covered with forms.
  • Never redirect to an address taken from user input.

 

What’s Next

Flash messages work because Laravel can remember something about a visitor between two requests. That memory is the session. In the next lesson, Sessions & Cookies, you will learn how sessions work, how to store and read your own values, and how cookies differ from sessions.

Frequently Asked Questions

If you show a page directly after a POST request, refreshing the browser sends the same data again, which can create duplicate invoices or orders. Redirecting to a GET page avoids this problem. It also gives the user a clean address in the browser.
Flash data lasts for exactly one more request. After the next page loads, Laravel removes it. If you need it to last longer, you can call reflash or keep, but this should be rare.
The with() method flashes any key and value you choose, such as a success message. The withInput() method flashes the data the user submitted, so you can fill the form again after an error. Both use the same one-time session storage.
A 302 redirect says the move is temporary, so browsers and search engines keep using the old address. A 301 redirect says the move is permanent, so search engines replace the old address with the new one. Laravel uses 302 by default, which is correct for form handling.
Yes. Use redirect()->away() with the full address, such as a payment provider page. For addresses inside your own app, use route names instead. Never build the address from user input, because that opens the door to phishing.

Share this tutorial