After saving a form, you redirect to another page and want to pass a message or some data along.
Flash data with with()
public function store(Request $request)
{
$data = $request->validate([
'name' => ['required', 'string', 'max:100'],
'email' => ['required', 'email'],
]);
$client = Client::create($data);
return redirect()
->route('clients.show', $client)
->with('status', 'Client created');
}
with() stores the value in the session for the next request only. Read it in the target:
session('status');
or in Blade:
@if (session('status'))
<div class="alert">{{ session('status') }}</div>
@endif
On the request after that, the value is gone. If you need it longer, use session()->put() or pass it in the URL.
Route parameters
IDs belong in the URL. Passing the model fills the route parameter:
return redirect()->route('clients.show', ['client' => $client->id]);
Validation failures
$request->validate() already redirects back with errors and old input when validation fails, and nothing is saved. Read errors with $errors in Blade and old values with old('name').
Test it
$this->post('/clients', ['name' => 'Ana', 'email' => 'ana@example.test'])
->assertRedirect(route('clients.show', Client::first()))
->assertSessionHas('status', 'Client created');
Tested on Laravel 10.x (PHP 8.1) and 12.x (PHP 8.3): the tests check the redirect target, the flash value, that it is readable once and then gone, and that invalid input saves nothing. Source: tests/laravel-verification/files/q664.