Dalton McCleeryDalton McCleery & Taylor RobbinsDalton McCleery & Taylor Robbins

Dalton McCleery

Full-Stack Web Developer and Laravel Artisan

Connect With Me

Podcasts

Back to HomeAll Blog Posts

Accessing Remote Models in Laravel

I finally did it. I made an open-source package. (Yay!)

This package was heavily inspired by Caleb Porzio's Sushi package. I did find one other, really old package of a similar concept called Remote Model by Torann that does something similar, but I wanted my package to be as "lean" and "streamlined" as possible.

The Idea

There may be times, albeit very rare, that you want to use an external data source or API as an Eloquent Model. Maybe you're building a microservice that needs access to the Users table of your main application or you have your "Find a Dealer" locations stored on your primary application but need to query that data somewhere else without the need to rebuild it and maintain it in two different places.

Enter: Remote Models.

My Problem

I've had a unique problem I was trying to solve with another upcoming project (no spoilers!) where I have a "single source of truth" application that is going to house the majority of my reusable data. I have other, smaller microservices that will need to "access" and query that data.

I could use a standard API solution using Laravel Sanctum, but then I have to wait on the API to return results for every call and maybe the data I want is on page 13 of the paginated results - so now I have to sift through multiple sets of data through multiple API calls just to get the piece of data I want.

So I could build myself a little wrapper class to handle all this for me, but the other problem is that once I do have that data - it's just a key->value array. I now need another wrapper to add some common Eloquent methods for it or wrap it in a collection, etc. It just gets messy.

I found myself thinking, "it would just be nice to have this data be it's own Eloquent Model, but I don't want to have duplicate or sharded data across my microservices." And if you know me, I hate writing the same thing twice.

So I built the Remote Models package.

How It Works

Taking heavy inspiration from Caleb's Sushi package, I thought if I could make all the necessary API calls upfront and then "cache" them locally (in a sqlite database file), I could just query that data as if it were a real Eloquent Model. Genius! So that's what I did. Again, big shout out to Caleb Porzio's Sushi package

Download It and Try It

Give the package a spin and let me know your thoughts (or open a PR with a feature!)

Remote Models

Sometimes you want to use Eloquent, but that data is in another database on a different application.