Adding Toastr Notifications in Laravel Application
I use Toastr notifications in almost all my web apps.
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.
$request->session()->flash('success', 'Post created 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 on using 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.
- Include css and js file from a CDN
- Install the library using NPM
- Download the css and js file from github Toastr Repository
However you choose the grab the library, you have to add the location to the 2 files in the head
tag of your master layout file like so:
After including the library, whenever you need to redirect to a page most probably from a controller, you can pass the notification information like so:
$notification = array( 'message' => 'Post created successfully!', 'alert-type' => 'success' ); return Redirect::to('/')->with($notification);
After adding redirect notification to your controller, add following javascript at the bottom of your layout file (app.blade.php or master.blade.php – depends on how you name it).
Note
Please open and close script tag before and after the below code snippet respectively.
@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
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 will be shown.