Is there solution to make laravel scout update index on relationship update?

I have multiple models in Laravel App that have related model “Tag” and I use a polymorphic many-to-many relationship with a pivot table. Now is there a way to force Algolia index update when relationship changes?

Hi @janic,

Currently, there is no built-in way. You will need to create to dispatch an event when you update a Tag, then implement the listener that will query and update all the relevant Model.
This should be something like Model::where('tag_id', "=", 2)->searchable().

https://laravel.com/docs/5.5/scout#updating-records

Please let me know if you manage to make it work.

@julienbourdeau, the problem is not in Tag model, but when I update Model relationship to Tag Model.

For example Model->tags()->sync([1,2,3]), will not touch Model, so Scout will not run re-indexing.
My solution, for now, is to compare attached Tags with ones coming from a request.

If there is a difference, I am running touch() method on a Model.

@julienbourdeau there is an even simpler solution already provided by Laravel.
https://laravel.com/docs/5.5/eloquent-relationships#touching-parent-timestamps

Thanks @janic !

I need to test this :slight_smile: I’m always amazed at how Laravel has a solution for every problem :tada:

Yeah, tested and this will work if the related model is attached already.
But if you have the option to attach tags on creation, then you need to run touch() method. And you need to make sure you added sleep(1) method before touch() because without that touch() method would not set updated_at. I guess everything happens soo fast to that created_at and update_at match .

1 Like

take a look at this package : https://github.com/fico7489/laravel-updated-related