laraveleloquentlaravel-scout

when using laravel scout, searchable() isn't updating related models


I am having an issue getting related models to update with scout elastic search.

$event->priceranges()->delete();
$event->priceranges()->Create([
       'price' => $ticket['ticket_price']
]);
$event->update([ 
      'show_times' => $request->showtimes,
]);
$event->searchable();

In my database I see the event and price range tables update. However when I look at my elastic search data, only data on the event has been updated. Any related models are not updated.

If I make a second update to the model and price range model, then the elastic search data shows my data from the first update I made (it is always one update behind for related models) I tried doing

$event->pricerange->searchable()

but gives me an error because I don't have a searchable index for pricerange, I am just using my event model and its relationship to index. Is there a way to force the update other than searchable()?


Solution

  • Looks like your relationship is being indexed in the Event model index, correct?

    Probably it's not being updated because the relationships are already loaded, and Laravel doesn't update the relationship data that is already loaded, for example:

    $event = Event::with('priceranges')->first()
    var_dump($event->priceranges->count()): // outputs for example 5
    
    $event->priceranges()->create([...]);
    var_dump($event->priceranges->count()): // still outputs 5, meaning that the created pricerange is not loaded
    

    So, to fix this issue you can reload the model before calling searchable():

    $event = $event->fresh();
    $event->searchable();
    

    But, note that everytime you update, the searchable method is already being called, so you will be indexing it two times on every update.

    So, alternatively you can update your toSearchableArray() method in Event model to get a fresh model before returning the data (I'm assuming that you are using the babenkoivan/scout-elasticsearch-driver).