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
Thanks,
please correct this line:
to
Hi, good catch! Thanks, updating now