Sanctum은 multiple model은 가능하지만 기본적으로 multiple DB를 지원하지 않는데

관리자 페이지에서 DB 3개 연동 및 간단한 인증 기능이 필요함

모델 분리

config/database.php 에서 connections 설정 후 별도의 model을 호출하면 해결 가능

<?php

namespace App; // your own namespace

use Laravel\\Sanctum\\PersonalAccessToken;

class PersonalAccessToken extends PersonalAccessToken
{
    protected $connection = 'my-connection';
    
    ...
    
}

미들웨어 설정

connections 설정을 변경하면 다른 database를 연결할 수 있다는 것을 확인

별도의 모델을 생성하거나 기존 모델을 분리하기 어려워 middleware에서 설정만 변경

namespace App\\Http\\Middleware;

use Closure;
use Illuminate\\Support\\Facades\\Config;
use Illuminate\\Support\\Str;

class DatabaseConnection
{
    private const DATABASES = ['aa', 'bb', 'cc'];

    public function handle($request, Closure $next)
    {
        if (config('app.env') === 'production') {
            $database = collect(self::DATABASES)
		            ->first(fn($value) => Str::contains($request->connection, $value));
            Config::set('database.connections.mysql.database', $database);
            // Exception
        }

        return $next($request);
    }
}