1

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

0

1 Answer 1

0

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for reply, Unfortunately, I was trying to customize the middleware on my own and was unable to achieve so because an older version of Laravel in the separate project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.