It seems like you are trying to play an audio alert when a new notification is received using Laravel Echo in a Filament PHP application. Your code snippet has a few issues that might be causing it not to work as expected. Here's a revised version of your code:
->renderHook('panels::body.end', function () {
$user = auth()->user();
if (!$user) {
return '';
}
if (method_exists($user, 'receivesBroadcastNotificationsOn')) {
$channel = $user->receivesBroadcastNotificationsOn();
} else {
$userClass = str_replace('\', '.', get_class($user));
$channel = "{$userClass}.{$user->getKey()}";
}
$escapedChannel = htmlspecialchars($channel, ENT_QUOTES, 'UTF-8');
return <<<BLADE
<script>
window.addEventListener('EchoLoaded', () => {
window.Echo.private('{$escapedChannel}').notification((notification) => {
// Replace this sound with your own sound/url.
var audio = new Audio('http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/alien_shoot.wav');
audio.play();
});
});
</script>
BLADE;
})
Here are the changes and considerations:
-
I've replaced
.listen('.database-notifications.sent', () => {with.notification((notification) => {. The.notificationmethod is used to listen for Laravel notifications being broadcast via Echo. -
I've removed the
setTimeoutfunction because it's not necessary for playing the sound. The sound will play as soon as the notification is received. -
I've added
htmlspecialcharsto escape the channel name to prevent XSS attacks. -
Make sure that the audio file URL is correct and accessible from the browser.
-
Ensure that your Laravel Echo setup is correctly initialized and that the
EchoLoadedevent is being fired. If it's not, the event listener won't be set up. -
Ensure that your Laravel backend is broadcasting notifications to the correct channel and that the user is authorized to listen to that channel.
-
Remember that modern browsers have restrictions on playing audio without user interaction, so this might not work unless the user has interacted with the page.
-
Ensure that the
BroadcastServiceProvideris uncommented in yourconfig/app.phpfile and that you have set up the necessary broadcast configuration in your.envfile. -
Make sure that your Laravel Echo server (Laravel WebSockets or Pusher) is running and properly configured.
Test this revised code, and it should play the audio alert when a notification is received.