vendredi 22 mars 2019

How to make an external API call response available to all model instances?

I have a Laravel app that lists travel trips along with their prices.

I'd like the prices to be in the local currency of the user based on her/his IP address.

Currently I have this code in the model:

    // Guzzle call to external api that returns exchange rates JSON
    $response = $client->request('GET','http://www.floatrates.com/daily/usd.json');

    //$userCurrency would be something like "EUR"
    $rate = json_decode($response->getBody()->getContents())->$userCurrency->rate;

    // I multiply exchange rate with the USD price to get price in local currency
    $priceInLocalCurrency = $usdPrice * $rate;

    // return price in local currency
    return $priceInLocalCurrency;

So far so good, however the process is very slow as the external API is called on every model instance returned. Which explains the slowness in populating travel trips - demo.

I have already seen this answer on how to make a variable accessible to all controllers by putting the variable (or api call response) in the BaseController:

https://stackoverflow.com/a/25194280/10278170

My goal is similar but to make a variable available to all model instances. So the external API is only called once.

Unlike controllers models extend this:

use Illuminate\Database\Eloquent\Model;

Which is located inside Vendor, so I can't add things to it.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire