To redirect back to the previous page with a message in Laravel, you can use the redirect()->back()
method and pass a key-value pair to the with()
method. The key will be the name of the variable that you want to use to store the message, and the value will be the message itself.
Here’s an example of how you can use this method to redirect back to the previous page with a message:
return redirect()->back()->with('success', 'Your message was sent successfully!');
This will redirect the user back to the previous page and store a message in the success
variable.
To display the message on the redirected page, you can use Laravel’s Session
class to retrieve the message. Here’s an example of how you can do this in a blade template:
@if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
This will display the message stored in the success
variable if it exists. You can use a similar approach to display other types of messages, such as errors or warnings, by using different keys and CSS classes.