Laravel Eloquent: keeping all interactions with a model in sync in two different databases

Viewed 285

I am working on a standard Laravel project (with a single MySQL database).

Now I need to keep in sync only one of my tables with another remote database. Thus, every change: creation, update, deletion, etc. in that specific table should be propagated / reproduced to the remote one in real time.

I have Googled before asking, but I haven't found a smart way to do it in Laravel apart from the obvious method which implies making every DB transaction to that model / table on both database connections.

By the way, I have seen the connection protected property of Eloquent ORM which sets a default DB connection for a specific model, but I am looking for something like having an array of values in that connection property.

No luck so far. Any thoughts? Thanks in advance.

1 Answers

If you are making all queries on eloquent models, then you could utilise eloquent events.

Inside your event listener/observer, you could clone the model and change the connection on the cloned model so that you can execute the query on the second database.

Related