Adding Toastr Notifications to your Laravel App

Adding Toastr Notifications to your Laravel App

Written by Dev Dojo on Jul 5th, 2016 Views Report Post

When a user signs up on your website or performs an action that needs a notification. A good option is to use the ToastrJS library. Checkout the demo here: http://codeseven.github.io/toastr/demo.html.

There are a few ways that you can include the js and the css file in your project. 

  1. Include the JS and the CSS library hosted on CDN JS
  2. Install the libraries via Bower
  3. Download the JS and the CSS file from the github repo: https://github.com/CodeSeven/toastr

However you decide to include it in your project you will then need to add the location to the 2 files in the <head> tag of your master layout file like so:

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

Then whenever you need to redirect to a page and pass a notification you can pass the redirect a notification array like so:

$notification = array(
	'message' => 'I am a successful message!', 
	'alert-type' => 'success'
);

return Redirect::to('/')->with($notification);

Then at the bottom of your master layout file (master.blade.php or app.blade.php) you will need to include the following javascript to show the notification type and the message you want to show:

<script>
  @if(Session::has('message'))
    var type = "{{ Session::get('alert-type', 'info') }}";
    switch(type){
        case 'info':
            toastr.info("{{ Session::get('message') }}");
            break;
        
        case 'warning':
            toastr.warning("{{ Session::get('message') }}");
            break;

        case 'success':
            toastr.success("{{ Session::get('message') }}");
            break;

        case 'error':
            toastr.error("{{ Session::get('message') }}");
            break;
    }
  @endif
</script>

And it's as easy as that. Make sure in the $notification array from step 2 that you specify whether you want the message to be an alert-type of info, warning, success, or error and the correct color notification will be shown.

Quick Note: If you are using Laravel 5.2 and your session messages are not passing. Make sure to wrap the route or method with the `web` middleware.

Post Image courtesy of The Brave Little Toaster

Comments (0)