Permalink
Browse files

Add broadcast channel

  • Loading branch information...
1 parent 2386f62 commit 8a2bc90638c4a063f208cc5df387a8e377ab8c0a @takayukii committed Dec 2, 2016
@@ -0,0 +1,51 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Events\MessageCreateBroadcastEvent;
+use App\Message;
+use Illuminate\Console\Command;
+
+class PushWebsocketNews extends Command
+{
+ /**
+ * The name and signature of the console command.
+ *
+ * @var string
+ */
+ protected $signature = 'websocket:news {text}';
+
+ /**
+ * The console command description.
+ *
+ * @var string
+ */
+ protected $description = 'Command description';
+
+ /**
+ * Create a new command instance.
+ *
+ * @return void
+ */
+ public function __construct()
+ {
+ parent::__construct();
+ }
+
+ /**
+ * Execute the console command.
+ *
+ * @return mixed
+ */
+ public function handle()
+ {
+ $arguments = $this->argument();
+ $text = $arguments['text'];
+
+ $message = Message::create([
+ 'text' => $text,
+ ]);
+ event(new MessageCreateBroadcastEvent($message));
+ return true;
+ }
+}
@@ -2,6 +2,7 @@
namespace App\Console;
+use App\Console\Commands\PushWebsocketNews;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
@@ -13,7 +14,7 @@ class Kernel extends ConsoleKernel
* @var array
*/
protected $commands = [
- //
+ PushWebsocketNews::class,
];
/**
@@ -0,0 +1,38 @@
+<?php
+
+namespace App\Events;
+
+use App\Message;
+use Illuminate\Broadcasting\Channel;
+use Illuminate\Queue\SerializesModels;
+use Illuminate\Broadcasting\PrivateChannel;
+use Illuminate\Broadcasting\PresenceChannel;
+use Illuminate\Broadcasting\InteractsWithSockets;
+use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
+
+class MessageCreateBroadcastEvent implements ShouldBroadcast
+{
+ use InteractsWithSockets, SerializesModels;
+
+ public $message;
+
+ /**
+ * Create a new event instance.
+ *
+ * @return void
+ */
+ public function __construct(Message $message)
+ {
+ $this->message = $message;
+ }
+
+ /**
+ * Get the channels the event should broadcast on.
+ *
+ * @return Channel|array
+ */
+ public function broadcastOn()
+ {
+ return new Channel('news');
+ }
+}
@@ -21,7 +21,12 @@
<div class="col-md-8 col-md-offset-2">
<ul>
<li v-for="message in messages">
- {{ message.created_at }} {{ message.text }} - {{ message.sender.name }} -> {{ message.receiver.name }}
+ <span v-if="message.type === 'news'" style="color: red;">
+ NEWS {{ message.created_at }} {{ message.text }}
+ </span>
+ <span v-else>
+ {{ message.created_at }} {{ message.text }} - {{ message.sender.name }} -> {{ message.receiver.name }}
+ </span>
</li>
</ul>
</div>
@@ -57,6 +62,13 @@
console.log(e);
this.messages.unshift(e.message);
});
+
+ Echo.channel('news')
+ .listen('MessageCreateBroadcastEvent', (e) => {
+ console.log(e);
+ e.message.type = 'news'
+ this.messages.unshift(e.message);
+ });
})
},

0 comments on commit 8a2bc90

Please sign in to comment.