3
4

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 5 years have passed since last update.

Laravel標準に認証にusers以外のテーブルを使う

Last updated at Posted at 2019-02-21

Laravelで利用者サイトと管理者(複数)サイトを作って同一のデータベースを共有したい場合などに
片方(管理者)用の認証用のテーブルをusers以外にしたい場合などの話

構成

サブドメインなどでドキュメントルートを切り分けてそれぞれ別のプロジェクトを作り同一DBを参照する
今回管理者認証用のテーブル名はmanagersとする

手順

認証機構を生成

$ php artisan make:auth

テーブルの生成

デフォルト配備されているでcreate_users_tableからcreate_managers_tableを作りテーブル名部分を書き換える

database/migrations/XXXX_XX_XX_XXXXXX_create_managers_table.php
-class CreateUsersTable extends Migration
+class CreateManagersTable extends Migration
{
    public function up()
    {
-        Schema::create('users', function (Blueprint $table) {
+        Schema::create('managers', function (Blueprint $table) {
            …
        });
    }

    public function down()
    {
-        Schema::dropIfExists('users');
+        Schema::dropIfExists('managers');
    }
}

マイグレート

基本的に同盟のマイグレーションファイルは読み込まれないのでそのまま実行してもよいがDB周りは片方のプロジェクトで一括管理した方がいいかもしれない

$ php artisan migrate

User.phpがvendor内のライブラリで呼ばれているようなのでこのファイルはそのまま流用した方がよさそう

app/User.php
    use Notifiable;
    // これで参照先のテーブルを変更
+    protected $table = 'managers';

    protected $fillable = [
        'name', 'email', 'password',
    ];

登録時にユニークチェックする対象がusersになっているので
app/Http/Controllers/Auth/RegisterController.phpも変更

app/Http/Controllers/Auth/RegisterController.php
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
-            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
+            'email' => ['required', 'string', 'email', 'max:255', 'unique:managers'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
        ]);
    }

あとホーム画面やトップ画面からRegisterメニューの削除などは任意に

3
4
1

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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?