Quantcast
Channel: 初心者タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 21089

Laravel Authのusersテーブルの情報を別のテーブルで管理する

$
0
0

目的

  • 本内容で非常に詰まったため記事としてまとめる

実施環境

  • ハードウェア環境
項目情報
OSmacOS Catalina(10.15.3)
ハードウェアMacBook Pro (16-inch ,2019)
プロセッサ2.6 GHz 6コアIntel Core i7
メモリ16 GB 2667 MHz DDR4
グラフィックスAMD Radeon Pro 5300M 4 GB Intel UHD Graphics 630 1536 MB
  • ソフトウェア環境
項目情報備考
PHP バージョン7.4.3Homwbrewを用いて導入
Laravel バージョン7.0.8commposerを用いて導入
MySQLバージョン8.0.19 for osx10.13 on x86_64Homwbrewを用いて導入

実施するに当たっての情報

  • usersテーブルで管理されている情報をpeopleテーブルで管理する。
  • 単純にusersテーブルで行われていた認証などの機能をpeopleテーブルで行うように切り替える。
  • peopleテーブルは新規作成するのでニュアンスは異なるが結果的にはAuthで使用するusersテーブルの名称変更に近い。
  • 本説明はDockerなどを使用せず、Macに直接環境構築を行い、そのローカル開発環境での実施を前提としている。
  • 本作業は下記の記事、またはそれに近い内容でAuthを用いたログイン機能を有しているLaravelのアプリケーションが存在している事を前提にまとめる。

実施方法概要

  • 既に存在するusersテーブルの代わりにpeopleテーブルを用いてAuthのログイン認証などを行う方法を記載する。
  1. usersテーブルの代わりになるpeopleテーブルの作成
  2. 設定の変更
  3. 確認

実施方法詳細

  • 既に存在するusersテーブルの代わりにpeopleテーブルを用いてAuthのログイン認証などを行う方法を記載する。
  1. usersテーブルの代わりになるpeopleテーブルの作成

    1. アプリ名ディレクトリで下記コマンドを実行してpeopleテーブルを操るモデルファイルとマイグレーションファイルを一緒に作成する。(本コマンドを若干詳しくした記事はこちら→Laravel モデルファイルと一緒にマイグレーションファイルも作成する)

      $php artisan make:model Person --migration
    2. アプリ名ディレクトリで下記コマンドを実行して先のコマンドで作成されたマイグレーションファイルを開く。(YYYY_MM_DDにはマイグレーションファイル作成日にちが、XXXXXXにはランダムな数字が入る。それぞれの環境にあったコマンドを実行する。)

      $vi database/migrations/YYYY_MM_DD_XXXXXX_create_people_table.php
      
    3. 開いたYYYY_MM_DD_XXXXXX_create_people_table.phpを下記のように修正する。修正後保存して閉じる。

      • 修正前

        アプリ名ディレクトリ/database/migrations/YYYY_MM_DD_XXXXXX_create_people_table.php
        <?phpuseIlluminate\Database\Migrations\Migration;useIlluminate\Database\Schema\Blueprint;useIlluminate\Support\Facades\Schema;classCreatePeopleTableextendsMigration{/**
             * Run the migrations.
             *
             * @return void
             */publicfunctionup(){Schema::create('people',function(Blueprint$table){$table->id();$table->timestamps();});}/**
             * Reverse the migrations.
             *
             * @return void
             */publicfunctiondown(){Schema::dropIfExists('people');}}
      • 修正後

        アプリ名ディレクトリ/database/migrations/YYYY_MM_DD_XXXXXX_create_people_table.php
        <?phpuseIlluminate\Database\Migrations\Migration;useIlluminate\Database\Schema\Blueprint;useIlluminate\Support\Facades\Schema;classCreatePeopleTableextendsMigration{/**
             * Run the migrations.
             *
             * @return void
             */publicfunctionup(){Schema::create('people',function(Blueprint$table){$table->id();//下記を追加$table->string('name');$table->string('email')->unique();$table->timestamp('email_verified_at')->nullable();$table->string('password');$table->rememberToken();//上記までを追加$table->timestamps();});}/**
             * Reverse the migrations.
             *
             * @return void
             */publicfunctiondown(){Schema::dropIfExists('people');}}
    4. アプリ名ディレクトリを下記コマンドで実行してマイグレートを行う

      $php artisan migrate
      
  2. 設定の変更

    1. アプリ名ディレクトリで下記コマンドを実行して先に作成したモデルファイルを開く。

      $vi app/Person.php 
      
    2. 開いたPerson.phpを下記のように修正する。修正後保存して閉じる。

      • 修正前

        アプリ名ディレクトリ/app/Person.php
        <?phpnamespaceApp;useIlluminate\Database\Eloquent\Model;classPersonextendsModel{//}
      • 修正後

        アプリ名ディレクトリ/app/Person.php
        <?phpnamespaceApp;//下記を追加と編集useIlluminate\Contracts\Auth\MustVerifyEmail;//下記を追加useIlluminate\Foundation\Auth\UserasAuthenticatable;//下記を追加useIlluminate\Notifications\Notifiable;classPersonextendsAuthenticatable{//下記を追加useNotifiable;/**
             * The attributes that are mass assignable.
             *
             * @var array
             */protected$fillable=['name','email','password',];/**
             * The attributes that should be hidden for arrays.
             *
             * @var array
             */protected$hidden=['password','remember_token',];/**
             * The attributes that should be cast to native types.
             *
             * @var array
             */protected$casts=['email_verified_at'=>'datetime',];//上記までを追加}
    3. アプリ名ディレクトリで下記を実行してauthの設定ファイルを開く。

      $vi config/auth.php 
      
    4. 開いたauth.phpを下記のように修正する。修正後保存して閉じる。

      • 修正前

        アプリ名ディレクトリ/config/auth.php
        <?phpreturn[/*
            |--------------------------------------------------------------------------
            | Authentication Defaults
            |--------------------------------------------------------------------------
            |
            | This option controls the default authentication "guard" and password
            | reset options for your application. You may change these defaults
            | as required, but they're a perfect start for most applications.
            |
            */'defaults'=>['guard'=>'web','passwords'=>'users',],/*
            |--------------------------------------------------------------------------
            | Authentication Guards
            |--------------------------------------------------------------------------
            |
            | Next, you may define every authentication guard for your application.
            | Of course, a great default configuration has been defined for you
            | here which uses session storage and the Eloquent user provider.
            |
            | All authentication drivers have a user provider. This defines how the
            | users are actually retrieved out of your database or other storage
            | mechanisms used by this application to persist your user's data.
            |
            | Supported: "session", "token"
            |
            */'guards'=>['web'=>['driver'=>'session','provider'=>'users',],'api'=>['driver'=>'token','provider'=>'users','hash'=>false,],],/*
            |--------------------------------------------------------------------------
            | User Providers
            |--------------------------------------------------------------------------
            |
            | All authentication drivers have a user provider. This defines how the
            | users are actually retrieved out of your database or other storage
            | mechanisms used by this application to persist your user's data.
            |
            | If you have multiple user tables or models you may configure multiple
            | sources which represent each model / table. These sources may then
            | be assigned to any extra authentication guards you have defined.
            |
            | Supported: "database", "eloquent"
            |
            */'providers'=>['users'=>['driver'=>'eloquent','model'=>App\User::class,],// 'users' => [//     'driver' => 'database',//     'table' => 'users',// ],],/*
            |--------------------------------------------------------------------------
            | Resetting Passwords
            |--------------------------------------------------------------------------
            |
            | You may specify multiple password reset configurations if you have more
            | than one user table or model in the application and you want to have
            | separate password reset settings based on the specific user types.
            |
            | The expire time is the number of minutes that the reset token should be
            | considered valid. This security feature keeps tokens short-lived so
            | they have less time to be guessed. You may change this as needed.
            |
            */'passwords'=>['users'=>['provider'=>'users','table'=>'password_resets','expire'=>60,'throttle'=>60,],],/*
            |--------------------------------------------------------------------------
            | Password Confirmation Timeout
            |--------------------------------------------------------------------------
            |
            | Here you may define the amount of seconds before a password confirmation
            | times out and the user is prompted to re-enter their password via the
            | confirmation screen. By default, the timeout lasts for three hours.
            |
            */'password_timeout'=>10800,];
      • 修正後

        アプリ名ディレクトリ/config/auth.php
        <?phpreturn[/*
            |--------------------------------------------------------------------------
            | Authentication Defaults
            |--------------------------------------------------------------------------
            |
            | This option controls the default authentication "guard" and password
            | reset options for your application. You may change these defaults
            | as required, but they're a perfect start for most applications.
            |
            */'defaults'=>['guard'=>'web',//下記を修正'passwords'=>'people',],/*
            |--------------------------------------------------------------------------
            | Authentication Guards
            |--------------------------------------------------------------------------
            |
            | Next, you may define every authentication guard for your application.
            | Of course, a great default configuration has been defined for you
            | here which uses session storage and the Eloquent user provider.
            |
            | All authentication drivers have a user provider. This defines how the
            | users are actually retrieved out of your database or other storage
            | mechanisms used by this application to persist your user's data.
            |
            | Supported: "session", "token"
            |
            */'guards'=>['web'=>['driver'=>'session',//下記を修正'provider'=>'people',],'api'=>['driver'=>'token',//下記を修正'provider'=>'people','hash'=>false,],],/*
            |--------------------------------------------------------------------------
            | User Providers
            |--------------------------------------------------------------------------
            |
            | All authentication drivers have a user provider. This defines how the
            | users are actually retrieved out of your database or other storage
            | mechanisms used by this application to persist your user's data.
            |
            | If you have multiple user tables or models you may configure multiple
            | sources which represent each model / table. These sources may then
            | be assigned to any extra authentication guards you have defined.
            |
            | Supported: "database", "eloquent"
            |
            */'providers'=>['users'=>['driver'=>'eloquent','model'=>App\User::class,],//下記を追加'people'=>['driver'=>'eloquent','model'=>App\Person::class,],// 'users' => [//     'driver' => 'database',//     'table' => 'users',// ],],/*
            |--------------------------------------------------------------------------
            | Resetting Passwords
            |--------------------------------------------------------------------------
            |
            | You may specify multiple password reset configurations if you have more
            | than one user table or model in the application and you want to have
            | separate password reset settings based on the specific user types.
            |
            | The expire time is the number of minutes that the reset token should be
            | considered valid. This security feature keeps tokens short-lived so
            | they have less time to be guessed. You may change this as needed.
            |
            */'passwords'=>['users'=>['provider'=>'users','table'=>'password_resets','expire'=>60,'throttle'=>60,],//下記を追加'people'=>['provider'=>'people','table'=>'password_resets','expire'=>60,'throttle'=>60,],],/*
            |--------------------------------------------------------------------------
            | Password Confirmation Timeout
            |--------------------------------------------------------------------------
            |
            | Here you may define the amount of seconds before a password confirmation
            | times out and the user is prompted to re-enter their password via the
            | confirmation screen. By default, the timeout lasts for three hours.
            |
            */'password_timeout'=>10800,];
    5. アプリ名ディレクトリで下記コマンドを実行してユーザ登録時に呼び出されるメソッドが記載されているファイルを開く。

      $vi app/Http/Controllers/Auth/RegisterController.php
      
      1. 開いたRegisterController.phpを下記のように修正する。修正後保存して閉じる。

        • 修正前

          アプリ名ディレクトリ/app/Http/Controllers/Auth/RegisterController.php
          <?phpnamespaceApp\Http\Controllers\Auth;useApp\Http\Controllers\Controller;useApp\Providers\RouteServiceProvider;useApp\User;useIlluminate\Foundation\Auth\RegistersUsers;useIlluminate\Support\Facades\Hash;useIlluminate\Support\Facades\Validator;classRegisterControllerextendsController{/*
              |--------------------------------------------------------------------------
              | Register Controller
              |--------------------------------------------------------------------------
              |
              | This controller handles the registration of new users as well as their
              | validation and creation. By default this controller uses a trait to
              | provide this functionality without requiring any additional code.
              |
              */useRegistersUsers;/**
               * Where to redirect users after registration.
               *
               * @var string
               */protected$redirectTo=RouteServiceProvider::HOME;/**
               * Create a new controller instance.
               *
               * @return void
               */publicfunction__construct(){$this->middleware('guest');}/**
               * Get a validator for an incoming registration request.
               *
               * @param  array  $data
               * @return \Illuminate\Contracts\Validation\Validator
               */protectedfunctionvalidator(array$data){returnValidator::make($data,['name'=>['required','string','max:255'],'email'=>['required','string','email','max:255','unique:users'],'password'=>['required','string','min:8','confirmed'],]);}/**
               * Create a new user instance after a valid registration.
               *
               * @param  array  $data
               * @return \App\User
               */protectedfunctioncreate(array$data){returnUser::create(['name'=>$data['name'],'email'=>$data['email'],'password'=>Hash::make($data['password']),]);}}
        • 修正後

          アプリ名ディレクトリ/app/Http/Controllers/Auth/RegisterController.php
          <?phpnamespaceApp\Http\Controllers\Auth;useApp\Http\Controllers\Controller;useApp\Providers\RouteServiceProvider;useApp\User;//下記を追加useApp\Person;useIlluminate\Foundation\Auth\RegistersUsers;useIlluminate\Support\Facades\Hash;useIlluminate\Support\Facades\Validator;classRegisterControllerextendsController{/*
              |--------------------------------------------------------------------------
              | Register Controller
              |--------------------------------------------------------------------------
              |
              | This controller handles the registration of new users as well as their
              | validation and creation. By default this controller uses a trait to
              | provide this functionality without requiring any additional code.
              |
              */useRegistersUsers;/**
               * Where to redirect users after registration.
               *
               * @var string
               */protected$redirectTo=RouteServiceProvider::HOME;/**
               * Create a new controller instance.
               *
               * @return void
               */publicfunction__construct(){$this->middleware('guest');}/**
               * Get a validator for an incoming registration request.
               *
               * @param  array  $data
               * @return \Illuminate\Contracts\Validation\Validator
               */protectedfunctionvalidator(array$data){returnValidator::make($data,['name'=>['required','string','max:255'],'email'=>['required','string','email','max:255','unique:users'],'password'=>['required','string','min:8','confirmed'],]);}/**
               * Create a new user instance after a valid registration.
               *
               * @param  array  $data
               * @return \App\User
               */protectedfunctioncreate(array$data){//下記を修正returnPerson::create(['name'=>$data['name'],'email'=>$data['email'],'password'=>Hash::make($data['password']),]);}}
  3. 確認

    1. アプリ名ディレクトリで下記コマンドを実行してローカルサーバを起動する。

      $php artisan serve
      
    2. 下記リンク先にアクセスする。

    3. 適当にテスト用のアカウント情報を入力して「Register」をクリックする。

      スクリーンショット 2020-04-17 18.22.54.png

    4. 下記の画面が出る事を確認する。

      スクリーンショット 2020-04-17 18.27.10.png

    5. 下記コマンドを実行してターミナルでMySQLにログインする。(MySQLのルートユーザのパスワードを忘れてしまった方はこちら→MySQL 8.0.18 のrootパスワードを忘れた時のリセット方法)

      $mysql -u root -p
    6. 下記を実行してPeopleテーブルに先ほど新規登録したデータが格納されている事を確認する。(データベース名一覧はmysql> show databases;で出力できる)

      mysql> select * from peopleテーブルがあるデータベース名.people;
      +----+------+---------------------+-------------------+--------------------------------------------------------------+----------------+---------------------+---------------------+
      | id | name | email               | email_verified_at | password                                                     | remember_token | created_at          | updated_at          |
      +----+------+---------------------+-------------------+--------------------------------------------------------------+----------------+---------------------+---------------------+
      |  1 | test | test.test@gmail.com | NULL              | $2y$10$pUYOp5TC6g/F./kRS4.OUu4hP5If0Eo6dI6P.8WydjEbqDDNXEzf6 | NULL           | 2020-04-17 09:26:59 | 2020-04-17 09:26:59 |
      +----+------+---------------------+-------------------+--------------------------------------------------------------+----------------+---------------------+---------------------+
      

Viewing all articles
Browse latest Browse all 21089

Trending Articles