0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

リアルタイムアプリケーションは、ユーザーに即時フィードバックを提供し、インタラクティブな体験を向上させるために重要です。今回は、Laravelを使用してリアルタイムアプリケーションを構築する方法について記述します。

目次

  1. リアルタイムアプリケーションの基本
  2. Laravel EchoとPusherの設定
  3. WebSocketの設定
  4. 実践プロジェクトの例

1. リアルタイムアプリケーションの基本

リアルタイムアプリケーションでは、クライアントとサーバー間で即時にデータを送受信します。これにより、チャットアプリケーションや通知システムなどが実現可能です。

2. Laravel EchoとPusherの設定

Laravel Echoは、Laravelアプリケーションにリアルタイム機能を追加するためのライブラリです。Pusherは、WebSocketを簡単に使用するためのクラウドサービスです。

Pusherの設定

  1. Pusherアカウントを作成し、新しいアプリケーションを設定します。
  2. Pusherのアプリケーションキーとクラスターを取得し、.envファイルに追加します。
PUSHER_APP_ID=your_app_id
PUSHER_APP_KEY=your_app_key
PUSHER_APP_SECRET=your_app_secret
PUSHER_APP_CLUSTER=mt1
BROADCAST_DRIVER=pusher

Laravel Echoのインストール

Laravel EchoとPusherのJavaScriptライブラリをインストールします。

npm install --save laravel-echo pusher-js

resources/js/bootstrap.jsでEchoとPusherを設定します。

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true
});

3. WebSocketの設定

WebSocketを使用してリアルタイム通信を実現します。ここでは、Laravel WebSocketsを使用してWebSocketサーバーをセットアップします。

Laravel WebSocketsのインストール

Laravel WebSocketsパッケージをインストールします。

composer require beyondcode/laravel-websockets
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
php artisan migrate
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

config/websockets.phpで設定を行います。

return [
    'apps' => [
        [
            'id' => env('PUSHER_APP_ID'),
            'name' => env('APP_NAME'),
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'path' => env('PUSHER_APP_PATH'),
            'capacity' => null,
            'enable_client_messages' => false,
            'enable_statistics' => true,
        ],
    ],

    'dashboard' => [
        'port' => env('LARAVEL_WEBSOCKETS_PORT', 6001),
    ],

    'ssl' => [
        'local_cert' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT', null),
        'local_pk' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_PK', null),
        'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),
    ],
];

WebSocketサーバーの起動

以下のコマンドでWebSocketサーバーを起動します。

php artisan websockets:serve

4. 実践プロジェクトの例

プロジェクト:リアルタイムチャットアプリケーション

  1. イベントの作成

php artisan make:event MessageSent

app/Events/MessageSent.php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use App\Models\Message;

class MessageSent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

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

    public function broadcastOn()
    {
        return new Channel('chat');
    }
}
  1. イベントのブロードキャスト設定

config/broadcasting.php

return [
    'connections' => [
        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'useTLS' => true,
            ],
        ],
    ],
];
  1. メッセージコントローラの作成

php artisan make:controller MessageController

app/Http/Controllers/MessageController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Message;
use App\Events\MessageSent;

class MessageController extends Controller
{
    public function sendMessage(Request $request)
    {
        $message = Message::create([
            'user_id' => $request->user()->id,
            'message' => $request->message,
        ]);

        broadcast(new MessageSent($message))->toOthers();

        return response()->json(['status' => 'Message sent!']);
    }
}
  1. フロントエンドの設定

Vue.jsコンポーネントを作成し、メッセージを送信・受信します。

resources/js/components/ChatComponent.vue

<template>
    <div>
        <div v-for="message in messages" :key="message.id">
            <strong>{{ message.user.name }}:</strong> {{ message.message }}
        </div>
        <input v-model="newMessage" @keyup.enter="sendMessage">
    </div>
</template>

<script>
export default {
    data() {
        return {
            messages: [],
            newMessage: ''
        };
    },
    mounted() {
        Echo.channel('chat')
            .listen('MessageSent', (e) => {
                this.messages.push({
                    user: e.message.user,
                    message: e.message.message
                });
            });
    },
    methods: {
        sendMessage() {
            axios.post('/messages', {
                message: this.newMessage
            }).then(response => {
                this.newMessage = '';
            });
        }
    }
};
</script>

routes/web.phpでルートを設定します。

Route::post('/messages', [MessageController::class, 'sendMessage']);

まとめ

この記事では、Laravelを使用したリアルタイムアプリケーションの構築方法について記述しました。Laravel EchoとPusher、WebSocketを使用して、リアルタイムチャットアプリケーションを構築する手順を学びました。これらの手法を駆使して、インタラクティブで即時性の高いアプリケーションを目指します。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?