Push Notification in laravel

In this tutorial, we will implement Push Notifications feature in our Laravel app using WebPush. We will use Vanilla Javascript with no frameworks or libraries. Push Notification is a feature of. A Service Worker is a script inside the web browser that runs in the background. There are a lot of features like caching , background syncing but this tutorial is only about Push Notifications. We will also implement push notifications for guest users.

Your Controller Code is This.

Step 1: BaseController.php

function send_push($push_arr, $msg, $type) {
 

$server_key = 'Your Firebase api key';
   
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" .       "$server_key");

    $notification = array('title' => 'your app name', 'text' => $msg, 'type' => $type);

    foreach ($push_arr['device_tokens'] as $token) {

        $arrayToSend = array(
            'to' => $token,
            'data' => $notification
        );

        $json = json_encode($arrayToSend);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        @$response = curl_exec($ch);
        print_r($response);

        }

    }

Step 2: UserContoller.php

function Masked($user_id) {
     $results = tbl_token::where('user_id', $user_id)->get(); 
      
     $this->send_push($user_id, $msg, $type);

 return $results;
}

Leave a Comment