Laravel

Laravel - Web socket - Pusher

1. Создать аккаунте на https://pusher.com

2. Создать вот это

3. Здесь теперь все написано что надо сделать



4. composer require pusher/pusher-php-server

5. В .env данные из аккаунта


6. php artisan make:event TestSocketEvent

<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class TestSocketEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;

public $message;

public function __construct($message)
{
$this->message = $message;
}

public function broadcastOn()
{
return ['my-channel'];
}

public function broadcastAs()
{
return 'my-event';
}
}


7. php artisan make:controller TestSocketController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Events\TestSocketEvent;

class SocketTestController extends Controller
{
public function test(Request $request) {
event(new TestSocketEvent('hello world'));
return "test";
}
}


8. Создать resources/views/test-socket.blade.php

<!DOCTYPE html>
<head>
<title>Pusher Test</title>
</head>
<body>
<h1>Pusher Test</h1>
<p>
Publish an event to channel <code>my-channel</code>
with event name <code>my-event</code>; it will appear below:
</p>
<div id="app">
<ul>
<li v-for="message in messages">
sdfsdfsdf
</li>
</ul>
</div>

<script src="https://js.pusher.com/8.2.0/pusher.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;

var pusher = new Pusher('c81fe52a5747885c0d6d', {
cluster: 'eu'
});

var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
app.messages.push(JSON.stringify(data));
});

// Vue application
const app = new Vue({
el: '#app',
data: {
messages: [],
},
});
</script>
</body>


9. В routes/web.php

Route::get('/test-socket', function () {
return view('test-socket');
});


10. В routes/api.php

Route::controller(SocketTestController::class)->group(function(){
Route::any('test','test');
});