Asynchronously update a model from a 'saved' event

Posted 2 years ago by harryg

I have the case where when an address in my app is created or updated, I want to geocode it. I use a 3rd party service for the geocoding so ideally this job would be performed asynchronously via a queued job so I can provide feedback to the user quickly and not fail the request if the geocoding service is down or failing. It's not important that the address has been geocoded by the next page.

So I have set up an event listener to dispatch the job every time an Address is created or updated:

\App\Address::saved(function($address) {
    dispatch(new \App\Jobs\GeocodeAddress($address));

In my job's handle method I simply query the api and update the Address:

public function handle(Geocoder $geocoder)
    $location = $geocoder->getCoordinates($this->address);

        'lat' => $location->lat,
        'lng' => $location->lng,

The problem with this approach is that it fires the saved event again which causes the same job to be dispatched thus causing an infinite loop of doom where I bombard the geocoding service with requests and cripple my database.

I could just use the saving event and simply set the values there but that would not allow me to do the geocoding asynchronously.

Can anyone suggest an elegant way to do this?

Please sign in or create an account to participate in this conversation.