Carlos Fdev Carlos Fdev - 1 year ago 99
reST (reStructuredText) Question

Fill models with Web Services

Having a basic example of a REST endpoint which returns a User json object, how would we fill our Model having that we get the data from a Web Service instead of a DB?

My approach is to have a very very basic 'SDK' with independent Classes with my data representation and access data methods, and in every method I make a call to the API with Guzzle to actually perform the action.

The problem is that I'm losing all the power that Eloquent provides.

Is there any recommended approach to do this in Laravel? Non Laravel approachs will do too.

Answer Source

I'd recommend to use a combination of cache and collections.

First you'll collect the web service results to a collection that you will then cache.

Something like this :

$users = Cache::remember('users', $minutes, function() use ($guzzle) {
    $apiUsers = $guzzle->get('api/users'); // Get the API response as json
    return collect(json_decode($apiUsers));

Using collections you'll have access to almost all of the Eloquent features (because it returns Collection as well. So you might do things like $user = $users->where('email', '')->first();

Then if you want to make it more like an "SDK", you can create a package that has classes and methods that makes it easier to get and use your API.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download