Implement Flash Message with Laravel 5.7
Flash messaging is a way to display an informative message to the user after they have performed a specific action on the website. Laravel provides an easy way to implement flash messages in your application using Laravel's Session
facade. In this article, we will explore the implementation of flash messages in Laravel 5.7.
Syntax
// To set a flash message
Session::flash('key', 'value');
// To get a flash message
Session::get('key');
Example
// To set a success message
Session::flash('success', 'Your request has been submitted successfully!');
// To set an error message
Session::flash('error', 'Sorry, there was an error. Please try again.');
// To get the message in the view
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
@endif
@if(Session::has('error'))
<div class="alert alert-danger">
{{ Session::get('error') }}
</div>
@endif
Output
When a success or an error message is set using the Session::flash()
method, the message will be available for the next request only. The message will then be cleared from the session.
Explanation
Flash messaging is useful when you want to inform the user about an action they have performed on the website. For example, when a user submits a form, you can display a message saying "Your request has been submitted successfully", or if there was an error, you can display a message saying "Sorry, there was an error. Please try again". Flash messages are also useful in directing the user to a specific part of the website, such as a confirmation page.
Use
Flash messaging can be used in any Laravel application to provide informative messages to the user. It can be used to provide feedback to the user after submitting a form, after deleting an item, or after any other action that requires feedback.
Important Points
- Laravel provides an easy way to implement flash messaging using the
Session
facade. - Flash messages can be used to provide informative feedback to the user.
- Flash messages are only available for the next request.
Summary
In this article, we explored the implementation of flash messages in Laravel 5.7 using Laravel's Session
facade. Flash messaging is a useful way to provide informative feedback to the user after they have performed a specific action on the website. With Laravel's Session
facade, implementing flash messaging in your Laravel application is easy and straightforward.