Now you can provide your feedback to our articles!

How to create real time notification in laravel without pusher

Last updated : Dec 12, 2021

How to create real time notification in laravel without pusher



Notification is an important part of today's web applications where applications are real time in nature. This article explains you also provides you with base scripts for creating real time notification in laravel without Pusher.

As the web has become the powerhouse of the software industry and primarily for those companies whose work is service based or freelance based work. Real time is the key component in almost all web apps now because each and every user wants information in real time.

So today we will see how to create real time notification in Laravel without Pusher. Let's start

  1. First let's create a project in any drive.

    laravel new realtime_notification

    Note : if you do not have Laravel installed, please read this article first.
  2. We will use a very good and performant package called beyondcode laravel-webockets package. It is built on the top of pusher package. That's why it uses random pusher credentials to run. So let's add this package to our project.

    composer require beyondcode/laravel-websockets

  3. Now we need another package called pusher-php-server. Type in command

    composer require pusher/pusher-php-server

  4. Now open .env file in any code editor and find

    BROADCAST_DRIVER=pusher
    . Then set pusher credentials
    PUSHER_APP_ID=12345
            PUSHER_APP_KEY=12345
            PUSHER_APP_SECRET=12345
            PUSHER_APP_CLUSTER=mt1

  5. Now let's publish migration file for storing the details of laravel-websockets package.

    php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"

  6. Migrate the database now. Enter command

    php artisan migrate

  7. Now let's publish config file for laravel-websockets package.

    php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

  8. Now let's start websockets server and test that if it is working fine. enter command

    php artisan websockets:serve

  9. Open browser and enter http://127.0.0.1:8000/laravel-websockets and you will get a dashboard like this :

  10. Now we will create an event which get triggered every time when notification has to be pushed. For that enter command

    php artisan make:event RealTimeMessage

  11. Open App/Events/
    RealTimeMessage.php and type in the following code:

        <?php
    
        namespace App\Events;
    
        use Illuminate\Broadcasting\Channel;
        use Illuminate\Broadcasting\PrivateChannel;
        use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
        use Illuminate\Queue\SerializesModels;
    
        class RealTimeMessage implements ShouldBroadcast
        {
            use SerializesModels;
    
            public string $message;
    
            public function __construct(string $message)
            {
                $this->message = $message;
            }
    
            public function broadcastOn(): Channel
            {
                return new Channel('events');
            }
        }
        
        

  12. Go to config/broadcasting.php file and type in the following script in pusher block.

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'encrypted' => true,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'http'
            ],
        ],
        
        

  13. Now we have completed the backend stuff now it's time to create frontend to receive the notification. We will be creating frontend in pure Javascript but it can be done in Laravel Echo.

  14. Open resources/views/
    welcome.blade.php and type in the following script.

    <!DOCTYPE html>
        <html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
    
                <title>Getting RealTime Notification</title>
                <meta name="csrf-token" content="{{ csrf_token() }}">
                <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    
                
            </head>
            <body class="antialiased">
    
                <div class="container">
                    <div style="display:none;" class="alert alert-success" id="notification_panel">kfdghfdkjgh</div>
                
                
                    <div class="jumbotron" style="margin-top:15px;">
                        <h1 class="display-4">Realtime Notification</h1>
                        <p class="lead">When you fire an event from websockets dashboard, you will receive notification here on the top.</p>                
                        </p>
                    </div>
                
                
                </div>
    
            </body>
    
            
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
            <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
            <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
    
            <script src="https://js.pusher.com/6.0/pusher.min.js"></script>
            <script>
            
            let a_tok = document.querySelector('meta[name="csrf-token"]').content;
    
        //suscribing to pusher channel
        Pusher.logToConsole = false;
        var pusher = new Pusher('12345', {
            cluster: 'mt1',
            broadcaster: 'pusher',
            //key: process.env.MIX_PUSHER_APP_KEY,
            //cluster: process.env.MIX_PUSHER_APP_CLUSTER,
            forceTLS: false,
            wsHost: window.location.hostname,
            wsPort: 6001,
        });
    
        var channel = pusher.subscribe('events');
        channel.bind('App\\Events\\RealTimeMessage',(d) => {
            if(d.msg == null || d.msg == ""){
                $("#notification_panel").removeClass('alert alert-success');
                $("#notification_panel").addClass('alert alert-danger');
                $("#notification_panel").text('Notification was blank');
                $("#notification_panel").fadeIn();
                setTimeout(function(){
                    $("#notification_panel").fadeOut();
                },2000);
            }
            else{                
                $("#notification_panel").removeClass('alert alert-danger');
                $("#notification_panel").addClass('alert alert-success');
                $("#notification_panel").text(d.msg);
                $("#notification_panel").fadeIn();
                setTimeout(function(){
                    $("#notification_panel").fadeOut();
                },2000);
            }
        });
            
            
            </script>
            </html>
            

Now scripting is done.
Its time to test. For testing open your app at 127.0.0.1:8000 in one window and laravel-websockets at 127.0.0.1:8000/laravel-websockets in another window.
Now in laravel websockets dashboard you will three fields :

In the first field type in the channel name you used in RealTimeMessage.php to broadcast your event.

In second field type in your event like this App\Events\RealTimeMessage.

And finally in the third field type in the message like this

{
        "msg":"this is sample notification"
    }


That is it for this article. Now you can also trigger the event from controller and also change the msg property text in json.



How video streaming works on t...

Read more

Setup react and express on sam...

Read more

How neurons in brain function

Read more

How to create custom router in...

Read more

Run C++ as CGI script in web b...

Read more

Real time chat application usi...

Read more

How to setup lemp stack in ubu...

Read more

How to secure phpmyadmin in Ub...

Read more

How to create simple api in no...

Read more

Task scheduling with cron job ...

Read more

How to use modules in Javascri...

Read more

Create a multi language(lingua...

Read more

Create food ordering app - Foo...

Read more

Linear Regression in machine l...

Read more

Create simple web application ...

Read more

Why algorithms can drive the i...

Read more

Why Javascript frameworks are ...

Read more

Create authenticated API in La...

Read more

Create simple and static websi...

Read more

Setup Pusher app

Read more

Laravel Installation and setti...

Read more

Realtime chat application in L...

Read more

Working of neurons (the easy w...

Read more

Progressive web app

Read more

Sign in for comment. Sign in