I've been struggling for a while now and can't find a way to make this work.
My project is on Laravel 8
I'm using Redis and laravel-echo-server (since it doesn't seem maintained I also tried with a hand-made express/socket.io server)
The problem : When I fire the event, it's received by Redis and Laravel Echo Server but it's never received on my webpage's console.
"Events/SendMessage"
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class SendMessage implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('user-channel');
}
public function broadcastAs()
{
return 'UserEvent';
}
public function broadcastWith()
{
return [
'title' => 'This notification is awesome'
];
}
}
".env"
BROADCAST_DRIVER=redis
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
LARAVEL_ECHO_PORT=6001
"welcome.blade.php"
<script>
window.laravel_echo_port='{{env("LARAVEL_ECHO_PORT")}}';
</script>
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>
<script src="{{ ('/js/laravel-echo-setup.js') }}" type="text/javascript"></script>
<script>
window.Echo.channel('user-channel').listen('.SendMessage', (e) => {
console.log('Got event...');
console.log(e);
});
</script>
"laravel-echo-setup.js"
import Echo from 'laravel-echo';
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ":6001"
});
Hope someone can help me
If you need anymore code, I'm here !!
Related
I am trying to use Pusher Notificaiton system to use web sockets to update the current page with the message "YOu have a new Notification" and the bell icon indicating the number of unread notifications. I registered the Events and Listeners and have implemented ShouldBroadcase and connected everything. But I am not getting any message. And unless the page reloads, I am not getting the no. of unread notifications as well.
Here are my codes
Event
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewNotificationEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
protected $data;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($data)
{
$data = $this->data;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return ['my-channel'];
}
public function broadcastAs()
{
return 'my-event';
}
}
Listener
<?php
namespace App\Listeners;
use App\Events\NewNotificationEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use DB;
use Illuminate\Support\Facades\Auth;
class NewNotificationListener
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param NewNotificationEvent $event
* #return void
*/
public function handle(NewNotificationEvent $event)
{
$users = Auth::user();
DB::select('CALL notification_tbl(?)',array($users->id));
}
}
Controller
if(Gate::allows('manage-users')){
$userid = $request->userid;
$notf = $request->notf;
$priority = $request->priority;
DB::table('notifications')->insert(['user_id'=>$userid,'notf_message'=>$notf,'priority'=>$priority]);
$data = array(
'userid'=>$userid,
'priority'=>$priority,
'notf_message'=>$notf,
);
event (new NewNotificationEvent($data));
// DB::select('CALL notification_tbl(?)',array($userid));
return response()->json([
'success'=>true,
'msg'=>"User Notified",
]);
}
abort(403, "This Page is only available for Admin");
}
}
Notification sent from Backend (Backend Controller)
public function sendNotf(Request $request){
if(Gate::allows('manage-users')){
$userid = $request->userid;
$notf = $request->notf;
$priority = $request->priority;
DB::table('notifications')->insert(['user_id'=>$userid,'notf_message'=>$notf,'priority'=>$priority]);
DB::select('CALL notification_tbl(?)',array($userid));
$data = array(
'userid'=>$userid,
'priority'=>$priority,
'notf_message'=>$notf,
);
// event (new NewNotificationEvent($data));
return response()->json([
'success'=>true,
'msg'=>"User Notified",
]);
}
abort(403, "This Page is only available for Admin");
}
JS Code (Available in the common blade page- the one which includes the Navbar and is included in every other page)
<script src="https://js.pusher.com/7.0/pusher.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('be850f6784915a1d43b8', {
cluster: 'ap2'
});
var channel = pusher.subscribe('user-channel');
channel.bind('user-channel', function(data) {
alert(JSON.stringify(data));
});
</script>
First of all, make your notification by php artisan make:notification exNotification
then implement your notification in toBroadcast function
return (new BroadcastMessage([
//
]))
Finally use
$user->notify(new exNotification());
Also, you can define your channel name in receivesBroadcastNotificationsOn in User Model
public function receivesBroadcastNotificationsOn()
{
return 'user.'.$this->id;
}
for more detail please visit :
Notifications
composer require pusher/pusher-php-server
PUSHER_APP_ID=322700
BROADCAST_DRIVER=pusher
// Get the credentials from your pusher dashboard
PUSHER_APP_ID=XXXXX
PUSHER_APP_KEY=XXXXXXX
PUSHER_APP_SECRET=XXXXXXX
//header or footer file
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//js.pusher.com/3.1/pusher.min.js"></script>
<script type="text/javascript">
var pusher = new Pusher('API_KEY_HERE', {
encrypted: true
});
// Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe('my-channel');
channel.bind('App\\Events\\NewNotificationEvent', function(data) {
console.log('New event');
//reload page for append data to any div
});
</script>
I am working with Laravel 7 with Vue.js, Laravel-echo and pusher.
when i call an event in vue i am receiving 500 (Internal Server Error)
bootstrap.js:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true
});
vue code
listen: function() {
Echo.channel('commentsChannel')
.listen('NewComment', (comment) => {
// this.comments.unshift(comment);
console.log('yessss');
})
}
Event: NewComment.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast; //for queueing
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; //for no queueing
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Comment;
class NewComment implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $comment;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Comment $comment)
{
$this->comment = $comment;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('commentsChannel');
}
}
routes/channels.php
<?php
use Illuminate\Support\Facades\Broadcast;
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Any Solution for this Error?! or How can we debug and know more about this error?!
Thank you in advance for helping!
bootstrap.js: give your key and cluster
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'XXXXXXXXXX',
cluster: 'XXX',
forceTLS: true
});
I have newly started working with laravel broadcasting and faced a problem. I am using Pusher and I want to check if users are authorized to subscribe to a private channel. Users' access to posts' comment notification is authenticated but not authorized. I am trying to send notification of new comment only to the post's author but all authenticated users who have opened the post get notifications. Am I missing something or what?
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class NewCommentEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public $comment;
public function __construct($comment)
{
$this->comment = $comment;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('post-'.$this->comment->post_id);
}
public function broadcastAs()
{
return 'new-comment-event';
}
public function broadcastWith()
{
return ['comment' => $this->comment->comment];
}
}
routes/channel.php:
<?php
use App\models\Post;
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('post-{id}', function ($user, $id) {
return false;
//return $user->id == Post::find($id)->author_id;
});
And the JavaScript in view:
var pusher = new Pusher('904d58ankty8c8397d000', {
authEndpoint: 'http://localhost/blog/public/broadcasting/auth',
cluster: 'ap2',
forceTLS: true,
auth: {
headers: {
'X-CSRF-Token': "{{csrf_token()}}"
}
}
});
var privateChannel = pusher.subscribe("private-post-{{{$post->id}}}");
privateChannel.bind('new-comment-event', function(data) {
$('#post-comments').append('<p>'+data.comment+'</p>');
});
By the way the following is the provider code:
public function boot()
{
Broadcast::routes(['middleware' => ['auth']]);
require base_path('routes/channels.php');
}
The laravel version i am using is: 5.8
What does "$this->comment->post_id" denote? If it denotes the id of that particular post, then who ever has access to that post will get the notification. Get author_id from post_id and Broadcast on 'post-'.author_id.
I am very new laravel broadcasting. I am working with redis, socket.io and laravel echo. When i reflesh the page this is write on console
GET http://localhost:6001/socket.io/?EIO=3&transport=polling&t=MloS95c
net::ERR_CONNECTION_REFUSED
My Test Event:
namespace App\Events;
use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class TestEvent {
use SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel ('Message');
}
}
My head :
<script src="http://{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
My Controller:
public function dev(){
event(new TestEvent("Hello"));
return view('home');
}
My Js file:
window.Echo.channel(`Message`)
.listen('TestEvent', (data) => {
console.log(data);
});
You are getting this error as the laravel echo server is not started. Inside your package.json file add under script the following line.
"scripts": {
"start": "laravel-echo-server start",
```
},
Now you need to go to the console and run npm start command into your project root directory. It will start the lavavel echo server and the error will be gone.
hi i am trying to connect with Socket.I.O vuejs laravel
in my App.js or Main.js code is
import io from 'socket.io-client';
import Echo from 'laravel-echo';
import VueEcho from 'vue-echo';
import VueSocketio from 'vue-socket.io';
window.io = require('socket.io-client');
const EchoInstance = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
Vue.use(VueEcho, EchoInstance);
In Channels.php
Broadcast::channel('test-event', function() {
return true;
});
Example event
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ExampleEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct()
{
return "Hello";
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('test-event');
}
public function broadcastWith()
{
return [
'data' => 'key'
];
}
}
in Routes web.php
Route::get('test-broadcast', function(){
broadcast(new \App\Events\ExampleEvent);
});
in my Components file
mounted() {
this.$echo.channel("test-event").listen("ExampleEvent", e => {
console.log(e);
});
}
according to
https://medium.com/#dennissmink/laravel-echo-server-how-to-24d5778ece8b
when i run
/test-broadcast
it have to give response in my about.vue browser console , but there is nothing to display at all. can any help what thing i am missing yet , Thanks in Advance
have you setup any queue driver? you will need to configure and run a queue listener. All event broadcasting is done via queued jobs.
or else you can use ShouldBroadcastNow interface.
change in you Example Event:
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
class ExampleEvent implements ShouldBroadcastNow
{ ...