Skip to main content

kritish-dhaubanjar/laravel-sanctum-websockets-spa

10 stars
4 code files
View kritish-dhaubanjar/laravel-sanctum-websockets-spa on GitHub

laravel/composer.json

Open in GitHub
{
//
"require": {
"php": "^7.3|^8.0",
"beyondcode/laravel-websockets": "^1.12",
//
"pusher/pusher-php-server": "~3.0"
},
//
}

laravel/app/Events/Chat.php

Open in GitHub
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 Chat implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
 
public $payload = 'Hello World!';
 
//
public function broadcastOn()
{
return new PrivateChannel('App.Models.User.1');
}
 
public function broadcastAs()
{
return 'new-message-event';
}
}

laravel/routes/api.php

Open in GitHub
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
 
Broadcast::routes(['middleware' => ['auth:sanctum']]);
//

vue-sanctum/src/App.vue

Open in GitHub
//
<script>
import axios from "axios";
import Pusher from "pusher-js";
import Echo from "laravel-echo";
console.log(Pusher);
export default {
name: "App",
data() {
return {
data: {
password: "secret",
},
};
},
async mounted() {
axios.defaults.withCredentials = true;
await axios.get("http://localhost:8000/sanctum/csrf-cookie");
await axios.post("http://localhost:8000/login", this.data);
const { data } = await axios.get("http://localhost:8000/api/user");
let echo = new Echo({
broadcaster: "pusher",
key: "s3cr3t",
wsHost: "localhost",
wsPort: 6001,
forceTLS: false,
cluster: "mt1",
disableStats: true,
authorizer: (channel, options) => {
console.log(options);
return {
authorize: (socketId, callback) => {
axios({
method: "POST",
url: "http://localhost:8000/api/broadcasting/auth",
data: {
socket_id: socketId,
channel_name: channel.name,
},
})
.then((response) => {
callback(false, response.data);
})
.catch((error) => {
callback(true, error);
});
},
};
},
});
echo
.private(`App.Models.User.${data.id}`)
.listen(".new-message-event", (message) => {
console.log(message);
});
},
};
</script>
//

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.