0
votes

I'm using three different databases with my Laravel backend, basically, one is for the backend itself, a second one is for a foo.com Nuxt website and the third one is a bar.com Angular website. Each of these three databases have a users table looking like this:

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Currently, each website is using Laravel Passport for authentification on the backend database. But now, I need the two websites foo.com and bar.com to use their own database users table for the authentification.

My Laravel Passport oauth_clients configuration looks like this:

+----+---------+------+---------------------------+----------+-----+
| id | user_id | name | secret | redirect         | provider | ... |
+----+---------+------+---------------------------+----------+-----+
|  1 |    null |  Foo | ****** | foo.com/callback |      foo | ... |
|  2 |    null |  Bar | ****** | bar.com/callback |      bar | ... |
+----+---------+------+---------------------------+----------+-----+

So, currently, users coming from foo.com sign in with their login/password through foo client and users coming from bar.com sign in with their login/password through bar client, but both on the backend users table.

How to force Laravel to use foo.users table for foo.com users and bar.users table for bar.com users ? Also, how to restrict foo users to use a foo middleware and bar users to use a bar middleware ?

1

1 Answers

0
votes

I believe you can achieve this by detecting the request hostname with $_SERVER['HTTP_HOST'].

Then you have to set up 3 different .env files for 3 different domains (.env, .foo.env and .bar.env), each with different database connection configurations.

At your bootstrap/app.php , you can add the code below:

$env  = '.env';
if ($_SERVER['HTTP_HOST'] == 'foo.com') {
    $env  = '.foo.env';
}
else if ($_SERVER['HTTP_HOST'] == 'bar.com') {
    $env  = '.bar.env';
}
$app->loadEnvironmentFrom($env);

I believe this is not the best option or best way to do it. But I believe you can achieve what you want with it.