Display message with session flash using bootstrap alert class in laravel

You can display alert messages in view files using the session flash in laravel 8. This code snippet helps you to add a bootstrap dynamic alert class (alert-success, alert-danger, alert-info) to show different types of messages for failures and success using session flash.

Answers 1
  • Display alert message with session flash in laravel 8

    //Import session facade in class
    use Illuminate\Support\Facades\Session;
    
    //Controller's method response after performing the task
    //Inside controller's method
    if(!$condition){
        Session::flash('message', 'Error message !'); 
        Session::flash('alert-class', 'alert-danger'); 
        return redirect()->back();
    }
    Session::flash('message', 'Success message !'); 
    Session::flash('alert-class', 'alert-success'); 
    return redirect()->back();
    
    //Display message with dynamic alert class in view file
    @if(Session::has('message'))
    <div class="alert {{ Session::get('alert-class', 'alert-info') }} alert-dismissible fade show">
        {{ Session::get('message') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    @endif
    
    0

    This code snippet helps you to show messages with bootstrap alert in the view file which is returned by the controller using session flash in Laravel 8. 

  • Back to code snippet queries related laravel

Related queries helps you to understand and may also used for implementation of current code snippet