Pusher Channels
Pusher Channels provides realtime communication between servers, apps and devices. Channels is used for realtime charts, realtime user lists, realtime maps, multiplayer gaming, and many other kinds of UI updates.
When something happens in your system, it can update web-pages, apps and devices. When an event happens on an app, the app can notify all other apps and your system.
Create account for yours at pusher.com like below:

Open your .env
and add Pusher Variables:
PUSHER_APP_ID=160127629
PUSHER_APP_KEY=7276e916fddd21e4320e87d
PUSHER_APP_SECRET=6c782c8gh85f352d78de
PUSHER_APP_CLUSTER=ap1
Update Composer
composer require pusher/pusher-php-server
Create uidPusher in your index.layout.blade.php (value pass from Controller or manually added)
<input id="uidPusher" value="3" type="hidden">
Create new file pusher.blade.php
and include in your index.layout.blade.php
template
{{-- realtime notif in apps like websockets --}}
<script src="{{ asset('asset-website/bundle/pusher/pusher.bundle.js') }}"></script>
<script>
if (document.getElementById("uidPusher") != null) {
const uid = document.getElementById("uidPusher").value;
const pusher = new Pusher("{{ env('PUSHER_APP_KEY') }}", {
cluster: "ap1",
encrypted: true,
});
var channel = pusher.subscribe(`admin-approve.${uid}`);
channel.bind(`foradmin`, function(data) {
console.log(JSON.stringify(data));
$(".badge-up").html("++Baru");
$(".loncheng").addClass("bx-tada bx-flip-horizontal");
toastr.success("New Notification", "Ada Permohonan Baru", {
closeButton: false,
debug: false,
newestOnTop: true,
progressBar: false,
positionClass: "toast-top-center",
preventDuplicates: true,
showDuration: "300",
hideDuration: "1000",
timeOut: "10000",
extendedTimeOut: "1000",
showEasing: "swing",
hideEasing: "linear",
showMethod: "fadeIn",
hideMethod: "fadeOut",
});
});
} else {
console.log('uidPusher not found')
}
</script>
BroadcastServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes(['middleware' => 'web']);
require base_path('routes/channels.php');
}
}
add to your channels.php
Broadcast::channel('admin-approve.{uid}', function ($user, $uid) {
return (int) $uid === (int) $user->id;
});
Setup Controller for Trigger Pusher
// SOMEWHERE IN YOUR CONTROLLERS
try {
$options = array(
'cluster' => 'ap1',
'useTLS' => true,
);
$pusher = new Pusher(
env('PUSHER_APP_KEY'),
env('PUSHER_APP_SECRET'),
env('PUSHER_APP_ID'),
$options
);
// Format: $pusher->trigger('channel-name', 'event-name','your-data');
$c = $pusher->trigger('admin-approve.' . $id_approver, 'foradmin', $data_hasil_validasi["data"]);
} catch (BroadcastException $e) {
$e->getMessage();
}
Testing from console

Pusher Beam
Beams offers native notification support for iOS, Android and web, so you can reach your users wherever they are

Open your .env
and add Pusher Variables:
BEAM_INSTANCE_ID=6cf308b9-78vf-4268-a921-d9a7660d4eb8
BEAM_SECRET_KEY=F4BC7AE26641985D9840B995XYDF94C3733F182F34D59D0B9B4FACE53050474ABC
Add into your web.php
<?php
use App\Http\Controllers\PusherBeamController;
Route::middleware(["web.role"])->group(function () {
Route::controller(PusherBeamController::class)->group(function () {
Route::group(['prefix' => 'beam'], function () {
Route::name("beam.")->group(function () {
Route::get('send-notif', 'send_notification')->name("sendNotification");
Route::get('get-token', 'get_token')->name("beam-get-token");
});
});
});
});
Create new Controller for generate Token called PusherBeamController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Pusher\PushNotifications\PushNotifications;
class PusherBeamController extends Controller
{
private $beam_secret;
public function __construct()
{
$this->beam_secret = array(
"instanceId" => env("BEAM_INSTANCE_ID"),
"secretKey" => env("BEAM_SECRET_KEY"),
);
}
public function get_token(Request $request)
{
if (!$request->has('user_id')) {
return response('Inconsistent request', 401);
} else {
try {
$beamsClient = new PushNotifications($this->beam_secret);
$beamsToken = $beamsClient->generateToken((string) $request->user_id);
User::where("id", $request->user_id)->update(['beam_token' => $beamsToken["token"]]);
return response()->json($beamsToken);
} catch (\Exception $e) {
report($e);
return response()->json([
'success' => false,
], 500);
}
}
}
public function send_notification(Request $request)
{
$title = $request->has("title") ? $request->title : "Test: title";
$body = $request->has("body") ? $request->body : "Test: Body";
$beamsClient = new PushNotifications($this->beam_secret);
$publishResponse = $beamsClient->publishToUsers(
[$request->user_id], [
"web" => [
"notification" => [
"title" => $title,
"body" => $body,
"icon" => "https://meeting.aplikasi-pintar.id/asset-website/images/ico/favicon.ico",
],
"data" => [
"name" => "everything, your",
"type" => "data goes here",
],
]
]);
return response()->json($publishResponse, 200);
}
}
Create new file pusher-beam.blade.php
and include in your index.layout.blade.php
template
{{-- pusher beam --}}
{{-- Desktop / Notif Mobile --}}
<script src="{{ asset('asset-website/bundle/pusherbeams/pusherbeams.bundle.js') }}"></script>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(function(registration) {
var currentUserId;
const beamsClient = new PusherPushNotifications.Client({
instanceId: "{{ env('BEAM_INSTANCE_ID') }}",
serviceWorkerRegistration: registration
});
const beamsTokenProvider = new PusherPushNotifications.TokenProvider({
url: "{{ route('beam.beam-get-token') }}",
});
var registered = false;
@if (!Auth::check())
localStorage.removeItem('Notif_Registered');
beamsClient.stop().catch(console.error);
@else
var cekRegistNotif = localStorage.getItem("Notif_Registered");
if (cekRegistNotif) {
console.log("Pusher Beam. This device registered");
} else {
beamsClient
.getDeviceId()
.then((deviceId) => {
if (deviceId == null) {
beamsClient.start()
.then(() => beamsClient.getDeviceId()
.then((deviceRg) => {
beamsClient
.getUserId()
.then((userId) => {
if (userId == null) {
@if (Auth::check())
currentUserId =
"{{ json_encode(auth()->user()->id) }}";
beamsClient.start().then(() => {
beamsClient.setUserId(
currentUserId,
beamsTokenProvider)
})
.catch(console.error);
@endif
}
})
})
);
}
@if (!Auth::check())
beamsClient.stop()
.catch(console.error);
@endif
})
.catch(console.error);
localStorage.setItem("Notif_Registered", true);
}
@endif
});
}
</script>
testing from console
