Адресный канал сокета (от конкретного пользователя, к конкретному пользователю)
Создадим контроллер UserController
Добавим соответствующий маршрут
routes/web.php
Код: Выделить всё
...
Route::get(uri: '/users/{user}', [\App\Http\Controllers\UserController::class, 'show']);
...
app/Http/Controllers/UserController.php
Код: Выделить всё
<?php
namespace App\Http\Controllers
class UserController extends Controller
{
public function show(User $user)
{
return inertia(component: 'User/Show', compact(var_name: 'user'));
}
public function sendLike(User $user, SendLikeRequest $request)
{
$data = $request->validated();
$likeStr = 'Your like from user with id ' . $data['from_id'];
broadcast(new SendLikeEvent($likeStr, $user->id))->toOthers();
return response()->json([
'like str' => $likeStr
]);
}
resources/js/Pages/User/Show.vue
Код: Выделить всё
<templates>
<div class="p-6 w-1/3 mx-auto">
<div class="mb-4">
User {{ user.name }}
</div>
<div class="mb-4">
<a @click.prevent="sendLike" href="#" class="rounded-gl block w-48 bg-sky-400 text-white text-center py-2">Send Like</a>
</div>
<div v-if="like_str">
{{ like_str }}
</div>
</div>
</templates>
<script>
export default
{
name: "Show" ,
props: [
'user'
],
data() {
return {
like_str: ''
}
},
//created() {
// console.log(this.$page.props.auth.user.id);
//},
created() {
window.Echo.channel(`send_like_${this.$page.props.auth.user.id}`)
.listen('.send_like', res => {
// console.log(res);
this.like_str = res.like_str
})
},
methods: {
sendLike(){
axios.post(`/users/${this.user.id}`, {from_id: this.$page.props.auth.user.id})
.then(res => {
this.like_str = res.data.like_str
})
}
}
}
</script>
<style scoped>
</style>
Маршруты:
routes/web.php
Код: Выделить всё
...
Route::get(uri: '/dashboard', function())
{
return Intertia::render(component: 'Dashboard');
})->middleware(['auth', 'verifed'])->name(name: 'dashboard');
Route::middleware(midleware: 'auth')->group(function () {
Route::get(uri: 'messages', [\App\Http\Controllers\MessageController::class, 'index']);
Route::post(uri: 'messages', [\App\Http\Controllers\MessageController::class, 'store']);
Route::get(uri: '/users/{user}', [\App\Http\Controllers\UserController::class, 'show']);
Route::post(uri: '/users/{user}', [\App\Http\Controllers\UserController::class, 'sendLike']);
Route::get(uri: '/profile', [ProfileController::class, 'edit'])->name(name: 'profile.edit');
Route::patch(uri: '/profile', [ProfileController::class, 'update'])->name(name: 'profile.update');
Route::delete(uri: '/profile', [ProfileController::class, 'destroy'])->name(name: 'profile.destroy');
});
require __DIR__.'/auth.php';
routes/channels.php
Код: Выделить всё
...
Broadcast::channel(channel: 'App.Models.User.{id}', function ($user, $id) {
return (int) $user->$id === (int) $id;
});
создаём метод запроса User/SendLikeRequest для контроллера UserController
Код: Выделить всё
php artisan make:request User/SendLikeRequest
app/Http/Requests/User/SendLikeRequest
Код: Выделить всё
<?php
namespace App\Http\Requests\User;
use Illuminate\Foundation\Http\FormRequest;
class SendLikeRequest extends FormRequest
{
public function authorize():bool
{
return true;
}
public function rules(): array
{
return [
'from_id' => 'required|integer|exists:users,id'
];
}
}
создадим событие SendLikeEvent
Добавляем интерфейс ShouldBroadcast для класса SendLikeEvent
app/Events/SendLikeEvents.php
Код: Выделить всё
<?php
namespace App\Events;
use ...
class SendLikeEvents implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
private string $likeStr;
private int $userId;
public function __construct(string $likeStr, int $userId)
{
$this->likeStr = $likeStr;
$this->userId = $userId;
}
public function broacastOn(): array
{
return [new Channel(name: 'send_like_' . $this->userId)];
}
public function broadcastAs(): string
{
return 'send_like';
}
public function broadcastWith(): array
{
return ['like_str' => $this->likeStr];
}
}