Search code examples
laraveleloquentlaravel-middlewarelaravel-sanctummulti-database

Laravel custom middleware for 2 databases


I don’t know how to create middleware for two databases tokens.

(First of all my english is not very well and I am beginner in laravel) I created a Laravel project that has two Eloquent Authenticatables that separate the database. I successfully saved tokens to personal access tokens for both databases, but I don’t know how to create middleware for those tokens. The first database (the default database) does not have any problems, but the second database does. Note 1: I’m using Sanctum for authentication. Note 2: The reason that I have to separate two databases is because my work requires


Solution

  • Try to make your own custom middleware. Middleware then inside the handle function instead of using eloquent. you may use DB queries to select another database.

    Modify your app/config/database.php like the following.

    <?php
    return array(
        'default' => 'mysql',
        'connections' => array(
            # primary
            'mysql' => array(
                'driver'    => 'mysql',
                'host'      => 'host1',
                'database'  => 'database1',
                'username'  => 'user1',
                'password'  => 'pass1'
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
            ),
    
            # secondary
            'mysql2' => array(
                'driver'    => 'mysql',
                'host'      => 'host2',
                'database'  => 'database2',
                'username'  => 'user2',
                'password'  => 'pass2'
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
            ),
        ),
    );
    

    Then in your middleware.

    <?php
     
    namespace App\Http\Middleware;
     
    use Closure;
    use Illuminate\Http\Request;
    use Symfony\Component\HttpFoundation\Response;
     
    class BeforeMiddleware
    {
        public function handle(Request $request, Closure $next): Response
        {
           // code here
           // DB::connection('mysql')->table('yourtable');
    
            return $next($request);
        }
    }