1

Is it possible to set foreign keys between tables of two different databases in laravel? it's possible

Shadow
  • 33,525
  • 10
  • 51
  • 64
  • Check out this other question: https://stackoverflow.com/questions/4452132/add-foreign-key-relationship-between-two-databases Laravel is just a framework using some relational database under the hood. – amucunguzi Sep 15 '20 at 16:51
  • You have to check first if you database supports it. – emiliopedrollo Sep 15 '20 at 17:32

2 Answers2

1

Cross database foreign keys hasn't much to do with Laravel actually.

MySQL (at least with InnoDB) does support foreign key constraints across multiple databases. You just have to specify the database with the dot notation:

Regarding the Laravel schema builder, this should work:

$table->foreign('user_id')->references('id')->on('main_db.users');
//                                                ^^^^^^^

If you get an error, check if the column types are the same.

You can't reference varchar to int or vice-versa, keys have to be of same type

Go through Foreign key cross database for more details

Ankit Jindal
  • 3,672
  • 3
  • 25
  • 37
0

IF, and only if your underlying database supports it, then there should be a way to translate this business rule to a Laravel app.

Maybe not using their fancy built-in ORM. But surely it's possible to write a migration for it using DB::statement or even DB::unprepared. But as the code for such a setup is not database agnostic this is against best practices, but not impossible.

You then must configure two (or more) connections, one for each database and use the property $connection on you models to tell Laravel on which database each model is. You will be able to even use Eloquent relations this way between models in different databases.

emiliopedrollo
  • 910
  • 6
  • 21