Share this:

Hello Dev, Today we are going to learn Laravel 9 Send Web Push Notification with Firebase Example. This tutorial will cover on how to send web push notification with firebase with example in laravel.

This article will give you simple example of FCM push notification in laravel 9. you will learn laravel 9 send push notification to android. you will do the following things for laravel 9 firebase push notification iOS.

Here, I will give you very simple steps to sending push notifications to the android and iOS app using laravel application. so basically your front-end mobile application provides you a devise token and you will store it in the database. Then you will use that device token to send push notifications using firebase laravel.

Steps for Laravel 9 Send Web Push Notification with Firebase Example:

  • Step 1: Install fresh new laravel 9 application
  • Step 2: Create Firebase Project and App
  • Step 3: Create Route
  • Step 4: Create Controller
  • Step 5: Update Blade File
  • Step 6: Testing
  • Step 7: Conclusion

Also Read: Laravel 9 Vue Js Roles and Permissions + Vite Js

Step 1: Install fresh new laravel 9 application

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Firebase Project and App

In first step, we have to go Firebase Console and create a project. then you have to create web app for that project as I added below screenshot:

Create Firebase Project and App
Create Firebase Project and App

After creating a successfully created app we will go to the setting page and get the server api key as like below screenshot:

Create Firebase Project and App
Create Firebase Project and App

You can copy that key and add on env file as below:

.env

FCM_SERVER_KEY=XXXXX

Also Read: Laravel 9 Stripe Payment Gateway Integration Example

Step 3: Create Route

Here, we need to add some routes to send push notifications so let’s add that route in the web.php file.

<?php
  
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\NotificationController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
   
Route::get('push-notification', [NotificationController::class, 'index']);
Route::post('sendNotification', [NotificationController::class, 'sendNotification'])->name('send.notification');

Step 4: Create Controller

Here, we need add index() and sendNotification() method for admin route in NotificationController.

In send notification() method we will get all device tokens from the user’s table and send a notification to the user. Make sure you have the “device_token” column in user’s table and add the token there.

now, so let’s add like as bellow:

app/Http/Controllers/NotificationController.php

<?php
 
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class NotificationController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('pushNotification');
    } 
  
     /**
     * Write code on Method
     *
     * @return response()
     */
    public function sendNotification(Request $request)
    {
        $firebaseToken = User::whereNotNull('device_token')->pluck('device_token')->all();
            
        $SERVER_API_KEY = env('FCM_SERVER_KEY');
    
        $data = [
            "registration_ids" => $firebaseToken,
            "notification" => [
                "title" => $request->title,
                "body" => $request->body,  
            ]
        ];
        $dataString = json_encode($data);
      
        $headers = [
            'Authorization: key=' . $SERVER_API_KEY,
            'Content-Type: application/json',
        ];
      
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
                 
        $response = curl_exec($ch);
    
        return back()->with('success', 'Notification send successfully.');
    }
}

Also Read: Laravel 9 integrate Razorpay Payment Gateway

Step 5: Update Blade File

In this step, we will create pushNotification.blade.php file with following code:

resources/views/pushNotification.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Laravel 9 Send Web Push Notification with Firebase Example - LaravelTuts.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<br/>
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Dashboard') }}</div>
                <div class="card-body">
                    @if (session('success'))
                        <div class="alert alert-success" role="alert">
                            {{ session('success') }}
                        </div>
                    @endif
                    <form action="{{ route('send.notification') }}" method="POST">
                        @csrf
                        <div class="form-group">
                            <label>Title</label>
                            <input type="text" class="form-control" name="title">
                        </div>
                        <div class="form-group">
                            <label>Body</label>
                            <textarea class="form-control" name="body"></textarea>
                          </div>
                        <button type="submit" class="btn btn-primary">Send Notification</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Also Read: How to Use Charts.JS in Laravel 9

Step 6: Testing

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://127.0.0.1:8000/push-notification

Preview:

Laravel 9 Send Web Push Notification with Firebase Example
Laravel 9 Send Web Push Notification with Firebase Example

Step 7: Conclusion

Today, We had learn Laravel 9 Send Web Push Notification with Firebase Example. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Laravel 9 JetStream Livewire CRUD Operations Tutorial

Share this:

Categorized in: