Laravel sanctum認証で使うusersテーブルの名称を変更する方法

例えば、usersではなくoperatorsに変更したい場合。

前提条件

・サンクタムを導入済みでユーザー登録用のapiだけ既に作成している

・Usersテーブルを利用する前提になっている

まずはコンテナに入ってテーブル名変更用パッチファイルを作成。

php artisan make:migration rename_users_to_operators_table

生成されたパッチファイルを下記のように編集

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class RenameUsersToOperatorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('operators', function (Blueprint $table) {
            Schema::rename('users','operators');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('operators', function (Blueprint $table) {
            Schema::rename('operators','users');
        });
    }
}

その後php artisan migrateコマンドでデータベースに反映させる。


backend/config/auth.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | 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' => 'operators',//変更
    ],

    /*
    |--------------------------------------------------------------------------
    | 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"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'operators',//変更
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | 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\Models\User::class,
        ],
                //追記ここから
       'operators' => [
           'driver' => 'eloquent',
           'model' => App\Models\Operator::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,
        ],
                //追記ここから
       'operators' => [
           'provider' => 'operators',
           '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,

];

User.php→Operator.phpにファイル名変更して編集

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;//ここはOperatorに置き換えない
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class Operator extends Authenticatable //変更
{
    use HasFactory, Notifiable, HasApiTokens;
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

登録用のコントローラー

RegistorController.php

<?php

namespace App\Http\Controllers\Api\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpFoundation\Response;
use App\Http\Controllers\Controller;
use App\Http\Requests\OperatorRegistRequest; //ここの名前を実際のファイルに合わせる
use App\Providers\RouteServiceProvider;
use App\Models\Operator;

class RegisterController extends Controller
{
    public function register(OperatorRegistRequest $request)
    {
        $defaultName = explode("@", $request->email);

        Operator::create([
            'name' =>  $defaultName[0],//初期値はemailの@マークより左側を入れたい
            'email' =>  $request->email,
            'password' => Hash::make($request->password),
        ]);
        return response()->json(['created' => true], Response::HTTP_OK);
    }
}

プロジェクトディレクトリ/app/Http/Requests/OperatorRegistRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class OperatorRegistRequest extends FormRequest //このファイル自身の名前に合わせる
{
    /**
     * Determine if the operator is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email'    =>  'required|email|max:255|unique:operators',//ユニークにしたいので「Rule::unique('operators')」
            'password' =>  'required',
        ];
    }
}

こんな感じで登録用APIは動作した。

ログイン用APIとかその他もろもろも、Controllerをそれっぽい書き方してあげれば普通に動くと思う。

「ログインはできるけど、ログインしているユーザーの情報が取得できない」って場合はこの記事見て。

sanctum認証でユーザー情報が取得できず401 Unauthorizedのエラー
↑別にテーブルの名前を変えたから動かなくなっているわけではない。

参考にしたサイト
https://note.com/code82/n/n3c92041140dc

無制限に質問可能なプログラミングスクール!

万が一転職できない場合は、転職保障全額返金できるコースもあり!!

無制限のメンター質問対応

 

DMMウェブキャンプでプログラミングを学習しませんか?

独学より成長スピードをブーストさせましょう!

 

まずは無料相談から!

おすすめの記事