Laravel Beginner Blade & HTTP · 6 min read

Laravel Session Flash Data

Lesson 32 of 33 in the Laravel learning path.

How do I show a one-time saved message after a redirect?

Flash data lives for the next request only. After that request, Laravel deletes it.

A saved message should appear once after the redirect, not on every later visit to the lesson.

Syntax & Parameters

Syntax
redirect()->route('lessons.show', $lesson)->with('status', 'Saved.')

Example

app/Http/Controllers/LessonController.php
<?php
function flashStatus(string $message): string
{
    session()->flash('status', $message);
    return (string) session('status');
}
function pullStatus(): ?string
{
    $value = session()->pull('status');
    return is_string($value) ? $value : null;
}
echo flashStatus('Lesson saved.'), PHP_EOL;
echo pullStatus() ?? 'gone', PHP_EOL;
echo pullStatus() ?? 'gone', PHP_EOL;

Expected Output

Lesson saved.
Lesson saved.
gone

Line-by-Line Walkthrough

  1. flash stores status for the following request.
  2. Reading it in the same request still sees it, which this sample does.
  3. pull reads and removes the key.
  4. The first pull prints the message.
  5. The second pull finds nothing and prints gone.
  6. A redirect with with() is the usual controller spelling.
  7. Blade should escape the status with curly braces.
  8. Do not flash an exception trace. Flash a short sentence.

Common Pitfalls & Security

Read the limits before you copy this.

  • Flashing HTML and printing it unescaped is XSS.
  • Forgetting the redirect means the message shows and is then gone before the user navigates.
  • Putting a large model in the flash bloats the session.
  • Two flashes of the same key keep only the last value.

Best Practices & Modern Standards

Flash a short status string and redirect.

Escape it in the template. Pull or let the next request consume it once.

Real-World Use

Saving a lesson redirects to the show page with Saved. Refreshing the show page does not repeat the banner.

Frequently Asked Questions

How long does flash last?

Until the next request reads the session, then it is removed.

What is with()?

A redirect helper that flashes the key for you.

How do I read it in Blade?

{{ session('status') }} inside a check so an empty flash prints nothing.

Can I flash an array?

Yes, a small array of field names is fine. Do not flash secrets.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…