In this post, we will look at how we can utilize the Laravel’s flash helper function to show toastr notifications in our application.

When user signup or sign in on your website, or perform an action, it’s always recommended to notify the user about progress from a UX point of view.

Laravel provides flash() helper to set the notification message which will be available on next HTTP request and then deleted. You can store notification in a session using the below method.

Session::flash('success', 'Post Updated Successfully.');
OR
session()->flash('success', 'Post Updated Successfully.');

 

Then you can access the session data using the below method and display to the user. 

{{ session('success') }}

Instead of using the above method, I rely like to use Toastr notification to show messages. Toastr is a javascript library to show notification in a modern way. You can check out the demo on the below link.

https://codeseven.github.io/toastr/demo.html

How to Add Toastr to Laravel

In this post, we will be adding Toastr to Laravel application, so let dive into it.

First thing first, you need to include the Toastr library to Laravel blade views. You can achieve this by below methods.

  1. Include css and js file from a CDN
  2. Incluse <script> code to call this Toastr

However, you have to add this following js and css CDN's to your master layout view file like so:

<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">

 

After including the library, you just need to add this following script code:

<script>
    @if(Session::has('success'))
        toastr.options = {
            "closeButton": true,
            "closeHtml": '<button><i class="fas fa-times"></i></button>',
        }
        toastr.success('{{ Session::get('success') }}')
    @endif
    @if(Session::has('errors'))
        toastr.options = {
            "closeButton": true,
            "closeHtml": '<button><i class="fas fa-times"></i></button>',
        }
        @foreach($errors->all() as $error)
            toastr.error('{{ $error }}')
        @endforeach
    @endif
    @if(Session::has('info'))
        toastr.info('{{ Session::get('info') }}')
    @endif
</script>

 

For your better understanding i used 3 types of notification Success, Errors, Info in this script. Where Success and Error section i also applied toastr.options but i don't use this in the Info section.

That’s it. Now if you visit or perform the action you have targeted, you will be shown a nice notification using toastr. You can set the alert type from info, warning, success or error and correct colored notification in the abobe script depends on your needs.