Here is a small snippet of code, which can be dropped into a helper.php
file.
function message_alert($timeout = 0) {
$return = '';
//If has errors
if( !empty(Session::get('errors')) ){
$return .= '<div class="fixed-bottom alert alert-danger mb-0"><div class="container">
<ul class="mb-0">';
foreach ( Session::get('errors')->all() as $error ):
$return .= '<li>'. $error .'</li>';
endforeach;
$return .= '</ul>
</div></div>';
} elseif( !empty(Session::get('message')) ) { //If not errors
//Split the Bootstrap alert class with message
list($type, $message) = explode('|', Session::get('message'));
$return .= sprintf('<div class="fixed-bottom alert alert-%s mb-0"><div class="container">%s</div></div>', $type, $message);
}
//If timeout is set, the alert should disappear
if( !empty($return) && $timeout > 0 ){
$return .= '<script>
jQuery(document).ready(function(e){
jQuery(".fixed-bottom.alert").delay('.$timeout.').slideUp(300);
});
</script>';
}
return $return;
}
Very often I’ll use a flash session message or input validation which will output error messages where applicable. By simply using {!! message_alert() !!}
I can output either with ease. This was added to my app.blade.php
file and therefore captures all success or error messages.
In a recent Laravel build I extended my original function to accept a variable for handling timeout, for example, {!! message_alert(5000) !!}
. This populates the jQuery code to hide the message after a period of time.
Using Bootstrap 4, I was able to use the standard alerts classes and fix the alert to the bottom of the screen.
return Redirect::back()->with('message', 'info|Successfully updated user');
The above example shows how you can use a pipe to split the type of alert with the message returned.