Skip to main content
Tutorial Free

Laravel Redirect to Route with (Error) Messages

June 27, 2023
2 min read

You've performed some action in Controller. Now you want to redirect the user to another page and show them the success/error message? Here are the options.

For a simple success message, just add ->with('[variable]', '[text_here]') to the redirect:

public function store(Request $request) {
// ...
 
return redirect()->route('tasks.index')
->with('message', 'Record added successfully!');
}

Then, in the Blade file, you will be able to access that 'message' value from the Flash Session, like session('message'):

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

Alternatively, of course, you may redirect the user to the page with a GET parameter like tasks?success=1, but it would be a security issue, as that parameter can be easily changed in the browser.


Redirect with Error Message(s)

If the Controller action failed and you need to redirect with error messages, you have two options.

Of course, you can do the same as above. Just name the variable error, something like this:

return back()->with('error', 'Something went wrong!');

But we can also use Laravel Validation functionality and populate the same Validation message manually:

return back()->withErrors(['email' => 'Email is invalid!'])->withInput();

Then you can display all the errors in Blade like this:

@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

I
ismaail ✓ Link copied!

Thanks,

please correct this line:

return back()->withErrors(['email', 'Email is invalid!'])->withInput();

to

return back()->withErrors(['email' => 'Email is invalid!'])->withInput();
M
Modestas ✓ Link copied!

Hi, good catch! Thanks, updating now

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.