Get Appointment

Blog Single

How to Integrate OneSignal Push Notifications in a Laravel Application

  • Vfix Technology
  • 24 Dec 2023
  • Laravel
  • 376 Views

Introduction

Push notifications are a powerful tool for engaging users and keeping them informed about important updates in your web application. OneSignal is a popular platform that provides a comprehensive solution for sending push notifications to web and mobile users. In this blog, we'll walk you through the process of integrating OneSignal push notifications into a Laravel application step by step.

Prerequisites

Before you get started, make sure you have the following prerequisites in place:

1. A Laravel application (if you don't have one, you can create a new one).

2. A OneSignal account (you can sign up for free at [onesignal.com](https://onesignal.com/)).

3. Basic knowledge of Laravel and web development.

Step 1: Create a OneSignal Account

If you haven't already, sign up for a OneSignal account. Once you're logged in, create a new app within OneSignal. This app will represent your Laravel application and allow you to send push notifications.

Step 2: Get Your OneSignal App Credentials

After creating your app in OneSignal, you'll need to obtain the following credentials:

- **App ID**: This is a unique identifier for your OneSignal app.
- **REST API Key**: This key is used to authenticate your server with the OneSignal API.

You can find these credentials in your OneSignal dashboard under **Settings > Keys & IDs**.

Step 3: Install the OneSignal PHP SDK

In your Laravel application, open the terminal and navigate to your project directory and install the package

composer require berkayk/onesignal-laravel

This package simplifies the integration of OneSignal into your Laravel app.

Now publish the package

php artisan vendor:publish --provider="Berkayk\OneSignal\OneSignalServiceProvider" --tag="config"

Now make the onesignal keys dynamic so user can edit or it dynamically form the admin panel

Step 1: To achive this create a model, controller, and migration

In Migration Add the below code 

$table->json('onesignal')->nullable();

This will store the data in the json formate

Step2: Now Create form to insert the data in the database 

@extends('adminlte::page')

@section('header')

@section('content_header')

@stop

@section('content')
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <!-- /.col -->
            <div class="col-md-9">
                <div class="card">
                    <form action="{{ route('setting.update', $setting->id) }}" method="post"
                        enctype="multipart/form-data">
                        @csrf
                        @method('PATCH')
                        <div class="card-body">
                            <div class="form-group row">
                                <label for="" class="col-sm-2 col-form-label">Site Key</label>
                                <div class="col-sm-10">
                                    <input type="text" name="onesignal[site_key]" id="" class="form-control"
                                        placeholder="Enter Site Key" value="{{ $setting->onesignal['site_key'] ?? '' }}">
                                    @error('onesignal[site_key]')
                                    <span class="text-danger">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="" class="col-sm-2 col-form-label">Secret Key</label>
                                <div class="col-sm-10">
                                    <input type="text" name="onesignal[rest_api_key]" id="" class="form-control"
                                        placeholder="Enter Secret Key" value="{{ $setting->onesignal[rest_api_key] ?? '' }}">
                                    @error('onesignal[rest_api_key]')
                                    <span class="text-danger">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                        <!-- /.tab-content -->
                        <div class="form-group row">
                            <div class="offset-sm-2 col-sm-10">
                                <button onclick="return confirm('Are you sure you want to update profile?');"
                                    type="submit" class="btn btn-danger">Update</button>
                            </div>
                        </div>
                    </form>
                </div><!-- /.card-body -->
            </div>
            <!-- /.card -->
        </div>
        <!-- /.row -->
    </div><!-- /.container-fluid -->
</section>
@stop

 

Setp3: Write the controller logic
 

<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use Illuminate\Http\Request;

class SettingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $setting = Setting::where('id',1)->firstOrFail();

        return view('backend.settings.index',compact('setting'));
       // dd($setting->toArray());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Setting  $setting
     * @return \Illuminate\Http\Response
     */
    public function show(Setting $setting)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Setting  $setting
     * @return \Illuminate\Http\Response
     */
    public function edit(Setting $setting)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Setting  $setting
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $data = $request->validate([
            'one_signal_rest_api_key' => 'nullable',
        ]);

        $setting = Setting::where('id',1)->firstOrFail();
        $setting->onesignal_rest_api_key = $request['one_signal_rest_api_key'];

        $setting->save();
        return redirect()->route('setting')->with('success', 'Settings Updated Successfully!');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Setting  $setting
     * @return \Illuminate\Http\Response
     */
    public function destroy(Setting $setting)
    {
        //
    }
}

After this you can insert the data and database 

Step 4: Pass the data in the config onesignal file

config/onesignal

To achive this open the AppServiceProvider in the providers folder and add the code.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Pagination\Paginator;
use App\Models\Setting;
use Config;
use View;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {

        $settingdata = Setting::where('id',1)->firstOrFail();

        // $contactform = $settingdata->captcha_contact_form;
        // $loginform = $settingdata->captcha_login_form;

       Config::set('onesignal.app_id', $settingdata->onesignal['site_key']);
       Config::set('onesignal.rest_api_key', $settingdata->onesignal['rest_api_key']);
    }
}

This will pass the keys in the config onesignal folder from the database 

Step 4: Setup push notification on the create of the post

Here I am expecting that you know crud in the laravel

Simply in the post controller you can use the below code 

    public function store(Request $request)
    {
        $data = $request->validate([
            'title'             => 'required|string|max:200',
            'slug'              => 'required|unique:posts',
            'image'             => 'nullable|image|mimes:jpg,png,jpeg,gif,svg,webp|max:2048',
            'excerpt'           => 'required',
            'body'              => 'required',

        ]);


        $post = new Post;
        $post->title                = $request->title;
        $post->slug                 = $request->slug;
        $post->excerpt              = $request->excerpt;
        $post->body                 = $request->body;


        if($request->file('image'))
        {
			//create unique name of image
            $imageName = time().'.'.$request->image->extension();

			//move image to path you wish -- it auto generate folder
            $request->image->move(public_path('uploads/images/post/'), $imageName);
            $post->image = $imageName;
        }

        $post->save();


            OneSignal::sendNotificationToAll(
                $post->title,
                $url = $post->slug,
                $data = null,
                $buttons = null,
                $schedule = null
            );

        return redirect()->route('post.index')->with('success','Post has beeen added successfully.');
    }

Here as the post will be created the notification will be send to the subscribers who have subscribed us similarly you can use it for different function at different actions. example: on delete, on update etc.



+91 8447 525 204 Request Estimate