Laravel でtwitterのフォロー機能を実装する

Laravelでtwitterのフォローのような機能を作る時は、以下のようなパッケージをcomposerでインストールして実装ができます。

しかし、このようなパッケージを入れなくてもtwitterのようなフォロー機能をシンプルかつ簡単に作成できます。

今回はLaravel 8.xにおいてtwitterのようなフォロー機能の実装方法をご紹介します。

目次

follower_userテーブルを作成

follower_userテーブルを作成するため、以下のコマンドを実行してください。

$ php artisan make:migration create_follower_user_table

follower_userでユーザーとフォロワーを関係付けます。
このテーブルは中間テーブルの働きをしますので、モデルを作成する必要はありません。

またfollower_userテーブルだけでフォロー、フォロワーがわかるので、followsテーブルを作る必要はありません。

follower_userマイグレーションを設定

follower_userテーブルのマイグレーションで以下のカラムを設定します。

  • user_id
  • follower_id

user_idは認証済みのユーザーID、follower_idは自分をフォローしているユーザーIDです。

このテーブルではidやタイムスタンプは必要ないので削除します。
マイグレーションファイルの設定は以下のようになります。

class CreateFollowerUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('follower_user', function (Blueprint $table) {
            // $table->id(); 削除
            $table->unsignedInteger('user_id'); // 追加
            $table->unsignedInteger('follower_id'); // 追加
            // $table->timestamps(); 削除
        });
    }

   ...
}

フォロー、フォロワーの取得

フォローやフォロワーを取得するにはUserモデルにリレーションを張ります。
フォローやフォロワーのリレーションを張ったUserモデルは以下のようになります。

<?php

namespace App\Models;

...

class User extends Authenticatable
{
    use HasFactory, Notifiable;
    ....

    /**
     * Relationships
     */
    public function follows()
    {
        return $this->belongsToMany(User::class, 'follower_user', 'follower_id', 'user_id');
    }

    public function followers()
    {
        return $this->belongsToMany(User::class, 'follower_user', 'user_id', 'follower_id');
    }

}

リレーションを張ることで以下のようにフォロー、フォロワーを取得することができます。

// フォローしているユーザーをすべて取得
$follows = auth()->user()->follows()->get();

// フォロワーをすべて取得
$followers = auth()->user()->followers()->get(); 

フォロー、フォロワーのダミーデータを入れる

follower_userテーブルにダミーデータを入れます。

フォローやフォロワーを追加するには以下のようにします。

// フォローを追加
auth()->user()->follows()->attach( User::find(1) );
// フォロワーを追加
auth()->user()->followers()->attach( User::find(2) );

すべてのユーザーを作成後にfollower_userテーブルにダミーデータを入れます。
UsersSeederは以下のようになります。

<?php
namespace Database\Seeders;

...

class UsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
     $faker = Faker::create('ja_JP');

        // ユーザーを50人作成
        $users = User::factory()->count(50)->create();

        foreach($users as $user) {
            // フォローを追加
            $user->follows()->attach( User::find($faker->numberBetween($min = 1, $max = 50)) );
            // フォロワーを追加
            $user->followers()->attach( User::find($faker->numberBetween($min = 1, $max = 50)) );
        }
    }
}

フォローやフォロワーを削除したい場合は以下のようにdetach()を使います。

// フォローを削除
auth()->user()->follows()->detach( User::find(1) );
// フォロワーを削除
auth()->user()->followers()->detach( User::find(2) );

おわり

twitterのフォロー機能が案外簡単に実装できました。

多様なサービスが展開されていますが、フォロー機能を実装したサービスが増えています。

是非参考にして下しさい。

https://laracasts.com/discuss/channels/eloquent/laravel-eloquent-followers-relationship?page=1&replyId=503340

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

コメント

コメントする


The reCAPTCHA verification period has expired. Please reload the page.

目次