Webアプリ習作#7
前々記事に引き続き主にこちらを参考にしました。 Laravel Socialiteを使ってTwitterアカウントでログイン機能 - Crieit
DBの方針
ユーザー情報はLaravelにデフォルトで用意されているusersテーブル(マイグレーション済み)の他にsocial_usersテーブルを新規に作成し、この2つで管理する social_usersには連携するSNS(今回のケースではTwitter)固有の情報が格納されusersデータ一つにつき複数個(連携するSNSの数ぶん)紐づけられる つまりusersとsocial_usersは一対多の関係にある(ただし、今のところTwiiterとしか連携しないので実質一対一の関係)
Doctrine DBALのインストール
DBの既存のカラムを修正するchangeメソッドの実行に必要なライブラリ プロジェクトディレクトリ上で下記を実行
composer require doctrine/dbal
social_usersテーブルの作成
プロジェクトディレクトリ上で以下を実行
php artisan make:migration create_social_users --create social_users
database/migrations下に[日付]_create_social_users.phpというファイルが生成されるので下記のように修正
public function up() { Schema::create('social_users', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('user_id')->unsigned()->index();// この行を追加. $table->string('provider_user_id')->index();// この行を追加. $table->timestamps(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');// この行を追加. }); }
上記のprovider_user_id
が連携SNS(Twitter)のユニークIDに相当する
usersテーブルの拡張
usersテーブルを生成するマイグレーションファイルは'2014_10_12_000000_create_users_table.php'(Laravelプロジェクト作成時に自動生成済み)だが、これとは別にusersテーブルを修正するマイグレーションファイルを作成する --createオプションの代わりに--tableオプションを指定する
php artisan make:migration add_social_columns_to_users --table users
[日付]_add_social_columns_to_users.phpというファイルが生成されるので編集
public function up() { Schema::table('users', function (Blueprint $table) { // ここからを追加. $table->string('unique_id')->after('id'); $table->string('avatar')->after('password'); $table->text('bio')->after('avatar'); $table->string('email')->nullable()->change(); $table->string('password')->nullable()->change(); // ここまでを追加. }); } public function down() { Schema::table('users', function (Blueprint $table) { // ここからを追加. $table->string('password')->change(); $table->string('email')->change(); $table->dropColumn('bio'); $table->dropColumn('avatar'); $table->dropColumn('unique_id'); // ここまでを追加. }); }
マイグレーションを実行
php artisan migrate
※エラー発生※
LogicException : Laravel v6 is only compatible with doctrine/dbal 2, in order to use this feature you must require the package "doctrine/dbal:^2.6".
Doctrine DBALがLarvel 6に対して新し過ぎるので、プロジェクトディレクトリのcomposer.jsonを開いてdoctrine/dbalの項目を以下のように修正
"doctrine/dbal": "^2.6",
更新して再度マイグレーション
composer update php artisan migrate
DBの確認
psqlを起動して追加されたことを確認する DBに接続
\c twiapp_db
テーブル一覧を確認
\dt
social_usersが追加されていることを確認 テーブルの中身を確認
\d social_users \d users