AppDividend
Latest Code Tutorials

Laravel Desktop Notification Implementation Tutorial

5,357

Get real time updates directly on you device, subscribe now.

Hello Developers, In this example, I will describe Laravel Desktop Notification Implementation Tutorial. I am using Pusher services to implement Desktop Notifications. For Frontend, I am using Vue.js. Real-time notifications are now very common in modern web applications as we need to keep users engaged and informed of happenings on their platform. In my blog: I am also using Desktop Notifications, but the service I am using is One Signal. It is also Good option to implement Desktop Push Notification.

In this tutorial, I am using Laravel and  Pusher to build a real-time app, with desktop notifications, utilizing the Notification API provided by the Browsers.

Laravel Desktop Notification Implementation

In general blog scenario, when the author post new article, all the subscribers get the notification about that latest post. We also implement the same scenario in which, we create a simple form to create a new article and then send a desktop push notification.

Step 1: Install Laravel 5.6

I am using Laravel Valet, so I am installing Laravel using the following command.

laravel new notify

If you are not using Laravel Valet software, then type the following command.

composer create-project laravel/laravel notify --prefer-dist

Go into the project.

cd notify

After that, Install the NPM dependencies using the following command.

npm install

Configure the database inside the .env file.

Step 2: Create Model, Controller and migration files.

Create a model and migration using the following command.

php artisan make:model Post -m

Write the following schema inside create_posts_table.

// create_posts_table

public function up()
{
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
}

Migrate the schema using this command.

php artisan migrate

Create a controller using the following command.

php artisan make:controller PostController

Step 3: Create a route and view file.

Inside routes >> web.php file, define the following route. It will redirect us to view the file.

// web.php

Route::get('post', 'PostController@create')->name('create');

Now, we need to store the data via an API so that we can define the store route inside routes >> api.php file.

// api.php

Route::post('post', 'PostController@store')->name('store');

Inside PostController.php file, write the following function.

// PostController.php

public function create()
{
    return view('post');
}

Now, create a blade file inside resources >> views folder called post.blade.php.

Write the following code inside a post.blade.php file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Simple Post</title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet"/>
</head>
<body>
    <div id="app">
        <form-component></form-component>
    </div>
    <script>
        window.Laravel = {!! json_encode([
        'csrfToken' => csrf_token(),
        ]) !!};
  </script>
  <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

Now, I have not written the form component yet, so I leave it here, but I will come back when we start building frontend with Vue.js.

Now, write the store function to save the post data in the database.

// PostController.php

public function store(Request $request)
{
     $post = new Post;
     $post->title = $request->get('title');
     $post->body = $request->get('body');

     $post->save();

     return response($post);
}

Step 4: Create an Event in Laravel.

Events are the great way to separate out a business logic. We can define events to be triggered in our application when an action occurs, and we can define listeners, to listen for such events.

Laravel allows for the exact definition of events and listeners out of the box. It also includes helper functions and classes to let us easily trigger and broadcast events.

Related Posts
1 of 39

Create an event using the following command.

php artisan make:event PostCreated

The PostCreated Event file is created inside App\Events folder.

Now, write the following code inside PostCreated file.

<?php

// PostCreated.php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\Post;

class PostCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $post;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    public function broadcastWith()
    {
        return [
          'title' => $this->post->title,
        ];
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('posts');
    }
}

Step 5: Install Pusher PHP Server.

Install pusher-php-server using the following command.

composer require pusher/pusher-php-server

Installing Laravel Echo and Pusher-js which we will use to listen for broadcasted events.

npm install -S laravel-echo pusher-js

Next, we will do some configuration to let Laravel know we will be using Pusher to manage our broadcasts. So, we need to add some credentials to integrate the API.

Now add the Pusher credentials inside the .env file.

BROADCAST_DRIVER=pusher

PUSHER_APP_ID=your_pusher_add_id
PUSHER_APP_KEY=your_pusher_app_key
PUSHER_APP_SECRET=your_pusher_app_secret
PUSHER_APP_CLUSTER=your_cluster

Step 6: Configure Frontend.

First uncomment the following code inside resources >> assets >> js >> bootstrap.js file.

 

// bootstrap.js
import Echo from 'laravel-echo'

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true
});

Rename the file inside resources >> assets >> js >> components folder called ExampleComponent.vue to FormComponent.vue file and add the following code inside FormComponent.vue file.

// FormComponent.vue

<template>
    <div class="container">
        <h3 style="margin-top:30px">Simple Desktop Push Notification Example</h3>
        <form style="margin-top:30px">
            <div class="form-group">
                <label>Title:</label>
                <input type="text" class="form-control">
            </div>
            <div class="form-group">
                <label>Body:</label>
                <textarea cols="8" rows="8" class="form-control"></textarea>
            </div>
            <button class="btn btn-primary">Submit</button>
        </form>
    </div>
</template>

<script>
    export default {
    }
</script>

Now, import this component inside resources >> assets >> js >> app.js file.

// app.js

require('./bootstrap');

window.Vue = require('vue');

Vue.component('form-component', require('./components/FormComponent.vue'));

const app = new Vue({
    el: '#app'
});

Add the form component inside a form.blade.php file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Simple Post</title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet"/>
</head>
<body>
    <div id="app">
        <form-component></form-component>
    </div>
    <script>
        window.Laravel = {!! json_encode([
        'csrfToken' => csrf_token(),
        ]) !!};
    </script>
  <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

Save the file and go to the terminal and type the following command.

npm run watch

Go to this URL: http://notify.test/post or http://localhost:8000/post

You can see the Form like this.

Laravel Desktop Notification Implementation Tutorial Example From Scratch

 

Step 7: Send a Post Request.

Okay, now we need to add some code inside FormComponent.vue component.

I am here writing the whole file to send a post request to the Laravel Server and save the data into the database.

// FormComponent.vue

<template>
    <div class="container">
        <h3 style="margin-top:30px">Simple Desktop Push Notification Example</h3>
        <form style="margin-top:30px" @submit.prevent="createPost">
            <div class="form-group">
                <label>Title:</label>
                <input type="text" class="form-control" v-model="title">
            </div>
            <div class="form-group">
                <label>Body:</label>
                <textarea cols="8" rows="8" class="form-control" v-model="body"></textarea>
            </div>
            <button
                :class="{ disabled: (!title || !body) }"
                class="btn btn-primary">
                    Submit
            </button>
        </form>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                title: "", 
                body: "" 
            }
        },
        
        methods: {
            createPost() {
                if(!this.title || !this.body)
                return;

                axios.post('/api/post', {
                    title: this.title, body: this.body
                    }).then( response => {
                    if(response.data) { 
                        this.title = this.body = "";
                    }
                })
            }
        }
    }
</script>

So, I have created two-way data binding to get the data from the form and check that data, if they are empty or not and then send the post request to the server. In the response, I have emptied all the fields.

Also, if you have not filled any fields then the submit button will be disabled and when all the fields are filled, it will enable so that you can submit the data to the server.

Save the file and try to submit the data and if everything works correctly, then you can save the data into the database.

Step 8: Listen for the event.

Now, inside FormComponent.vue file, you have to add the event listeners.

I am writing the final code inside FormComponent.vue file.

// FormComponent.vue

<template>
    <div class="container">
        <h3 style="margin-top:30px">Simple Desktop Push Notification Example</h3>
        <form style="margin-top:30px" @submit.prevent="createPost">
            <div class="form-group">
                <label>Title:</label>
                <input type="text" class="form-control" v-model="title">
            </div>
            <div class="form-group">
                <label>Body:</label>
                <textarea cols="8" rows="8" class="form-control" v-model="body"></textarea>
            </div>
            <button
                :class="{ disabled: (!title || !body) }"
                class="btn btn-primary">
                    Submit
            </button>
        </form>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                title: "", 
                body: "" 
            }
        },
        created() {
            this.listenEvent();
        },
        methods: {
            createPost() {
                if(!this.title || !this.body)
                return;

                axios.post('/api/post', {
                    title: this.title, body: this.body
                    }).then( response => {
                    if(response.data) { 
                        this.title = this.body = "";
                    }
                })
            },
            listenEvent() {
                    Echo.channel('posts')
                    .listen('PostCreated', post => {
                        if (! ('Notification' in window)) {
                        alert('Web Notification is not supported');
                        return;
                        }

                        Notification.requestPermission( permission => {
                        let notification = new Notification('New post alert!', {
                            body: post.title
                        });

                        notification.onclick = () => {
                            window.open(window.location.href);
                        };
                    });
                });
            }
        }
    }
</script>

So, when the PostCreated event is triggered by Laravel, it listened by this function listenEvent.

Now, if the permission is given by the browser, then it will sure give a notification about the latest post.

Note: Firefox and Safari are right now supported to receive the push notification on HTTP origin. Google Chrome is not supported. It will give you the deprecation warning to use HTTPS version of your site. I have not checked Edge or IE.

Finally, We have implemented primary Desktop Push Notification in Laravel using Vue and Pusher service.

The Laravel Desktop Notification Implementation Tutorial is over. Thanks for taking.

11 Comments
  1. WAleed says

    Very cool. Please do some more real world examples like this. Thanks.

    1. Krunal says

      Thanks and will try my best.

  2. Cesar Ureño says

    The best. Thank you for your tuto. Can you create a tuto with redis instead pusher.

  3. kingpoker88 says

    You can definitely see your expertise in the article you write.
    The world hopes for even more passionate writers like you who are
    not afraid to mention how they believe. At all times follow your heart.

  4. LuckyLa says

    Hi,
    nice tutorial, most appreciated, but for some reason I can’t save to database/method createPost isn’t called at all, I’m not sure why.

  5. Simon Fattal says

    Thanks so much this really helped.
    Quick question: once I send a notification from the form on the localhost page, where can I see it?
    Also, is it possible to have these notifications show up on some external site? Eg, my website showing notifications whenever a form is sent.
    Many thanks!

  6. Simon Fattal says

    Is there a way to see a database of all sent notifications?

  7. Simon Fattal says

    Hi. I just completed your tutorial: Laravel Desktop Notification Implementation Tutorial.
    I have the front end site working where I send notifications, which is great.
    However, I would like to be able to view all notifications I have sent, in some database. Is this possible? you mention it in Step 7 but I didn’t really understand what you meant. I just want to see everything I have sent to prevent me from accidentally sending duplicates.
    Thanks
    Simon

  8. Palash Chanda says

    How is the event being triggered?

  9. Danijel says

    Hey Krunal,

    thanks for writing this tutorial,
    can you please help me with it more, as I dont see where you are triggering event in postcontroller?

  10. Ap says

    Thanks man you save my time

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.