0
votes

Using Laravel's Eloquent Model, how can I update an object's data upon accessing it, if it has been > 30 days since it's last updateDate?

I have another API that I want to make sure the data is semi up-to-date with, but would like to cache the data in my database rather than call their API every page load.

Is there any function that Laravel calls every time the model is loaded, where I could check if 30 days have passed, call the API to load the new data, and then save it?

1
a cron job each 30 days?Ezequiel Moreno

1 Answers

1
votes

It's not clear how you use the data from the API, but you may find Laravel's caching capabilities quite handy. Specifically remember() method.

use Illuminate\Support\Facades\Cache;

// Put the result returned from the closure in the cache for 30 days
// under the key 'apidata' and serve this data off of cache if it already there
$apidata = Cache::remember('apidata', 60*24*30, function() {
        // talk to your API
        // and return the data from this closure
        return $result;
});

You can make a step further and wrap it in a service class to make your life easier. Something along the lines of

namespace App;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

class ApiData
{
    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function all()
    {
        return Cache::remember('apidata', 60*24*30, function() {
            $response = $this->client->get('http://httpbin.org/get');
            return $response->getBody()->getContents();
        });
    }
}

Then use it

// Get an instance off of IoC container
$api = app('App\ApiData');
$apidata = $api->all();