LoginSignup
1
2

More than 3 years have passed since last update.

Laravel+React でpusherを使う

Posted at

バージョンは
laravel 6
react 16.14. 0
npm 7.5.3

laravelのconfig\app.phpの

config\app.php
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\BroadcastServiceProvider::class, <- コメントアウト解除
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,

.envの

BROADCAST_DRIVER=pusher に変更
resources/js/bootstrap.js
/*全てコメントアウト*/
import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

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

自分のlaravelのフォルダ直下で以下のコマンドを実行
ターミナル

$ composer require pusher/pusher-php-server

pusherに登録してください
https://pusher.com/

create-appを押してアプリを作成

スクリーンショット 2021-04-11 19.42.19.png

この画面になったら
・アプリ名
・フロントまたはバックエンドの使用している言語を選択してCreate appを押す

作成したアプリのApp Keysを見る
app_id
key
secret
clusterをコピー

.envで

/.env
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=
ここにコピー

ターミナルで

$ php artisan make:event PostCreated

ここから個人の開発によって違いますがなるべくわかりやすく説明します

app/Events/PostCreated.
<?php

namespace App\Events;

use App\Post; <-自分はここを追記
use App\User; <-自分はここを追記
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 PostCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $post;
    public $user;

    public function __construct(Post $post, User $user)
    {
        $this->post = $post;
        $this->user = $user;
    }

    public function broadcastOn()
    {
        return [
            new PrivateChannel('new-post'),
            new PrivateChannel('App.User.'.$this->post->user->id),
        ];
    }

    public function broadcastWith() {
        return [
            'post' => array_merge($this->post->toArray(), [
                'user' => $this->post->user,
            ]),
            'user' => $this->user,
        ];
    }
}

use App\Postで自分が欲しい情報をとってきています
broadcastOnにPrivateChannel('new-post')があると思います
これはreact側で呼び出すための鍵です

使用しているControllerに飛びます
app\Http\Controllers

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\Events\PostCreated; <-追記

public function create(Request $request,Post $post) {
  $createdPost = $request->user()->posts()->create([
     'body' => $request->body,
  ]);

  broadcast(new PostCreated($createdPost, $request->user()))->toOthers(); <-これを追記 

  return response()->json($post->with('user')->find($createdPost->id));
}

routes/channels.php
/*追記*/
Broadcast::channel('new-post', function ($user) {
    return Auth::check();
});

reactで

resources/js/app.js
useEffect(() => {
    window.Echo.private('new-post').listen('PostCreated', e => {
      if (window.Laravel.user.following.includes(e.post.user_id)) {
        setPosts([e.post, ...posts])
      }
    })
  }, [])

自分はtwitterアプリを作ったのでメッセージが届いたら表示するために
setPosts()で更新をかけています

pusherはかなりハマりやすいと思います
公式ドキュメントhttps://readouble.com/laravel/5.8/ja/broadcasting.html

1
2
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
1
2