In yesterday's article, we looked at how Eloquent models boot up and how the constructor works.

However, you may have been scratching your head when you saw that this massively powerful ORM did nothing to work with persistence or database interactions at all. In fact, that is completely true: if you use Eloquent with just the constructor, you have an excellent stateless model instance (I'll be going over when this would be useful in a later article). But, today, we will get into the bulk of the Eloquent persistence layer - the connection.

To start looking at connections we will start in the save function as it is the first interaction you will have with a Eloquent store assuming you do not have an existing filled DB. In the first line of save, we see that we have to call newQueryWithDeleted, which simply calls newQuery but tells it to grab a soft-deleted records as well (in case we are updating a soft-deleted record). From here we start to look at building our Eloquent query builder passing in a call to newBaseQueryBuilder.

Finally, in newBaseQueryBuilder we see that we grab a Connection and Query Grammar in order to create an instance of Fluent query builder. It is in the call to getConnection that we can really make Eloquent flex its muscles with just a small bit of customization.

You can set the connection property on a model and quickly change that model from working off of your application's default connection to something else. If you recall, we made a similar hack in the post on database flexibility in packages. So, if you want your tags in a shared mySQL database while your posts reside in a local PostgreSQL instance, go ahead and set your connections and you are done.

But, the connection magic does not end there. In fact, Eloquent lets you change connections on the fly by using the setConnection function and passing the connection name you want to use. Similarly, if you decided to use connections by themselves in some custom bit of code you can always run getConnection. However, I think you'd likely be better off by grabbing the Fluent builder with newBaseQueryBuilder.

Tomorrow, we will look a bit more at how the Fluent Query Builder differs from the Query Builder that runs Eloquent.