Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Add 'makeSearchableUsing' method (to allow eager loading when making specific models searchable) #732

Conversation

gdebrauwer
Copy link
Contributor

@gdebrauwer gdebrauwer commented Apr 24, 2023

In the projects at work, we use Laravel's lazy loading prevention. But when installing and using Scout, I noticed that Scout does not use makeAllSearchableUsing when making specific models searchable (which I thought at first). This causes lazy loading errors when the toSearchableArray method expects certain relations to be loaded (as is the case when importing all models because it then uses the makeAllSearchableUsing method).

public function toSearchableArray() : array
{
    return [
        // This causes lazy loading on every model that is made searchable
        'some_relation_attribute' => $this->someRelation->attribute
    ];
}

$someModels->searchable();
$parentModel->someRelation()->searchable();

So to fix this, I propose introducing a new method: makeSearchableUsing. This method allows you to modify models before the toSearchableArray method is called on each of those models

protected function makeSearchableUsing($models)
{
    // load relations or add extra data that will be used in the "toSearchableArray" method
    return $models->load(...);
}

@taylorotwell
Copy link
Member

Can't you just call load on the collection before calling searchable?

@gdebrauwer
Copy link
Contributor Author

No that does not work when data syncing is queued. And even if it would work, it would be very annoying in my opinion. You might have to make models searchable in different places, which means you have to repeat the eager loading code in all those places.

@taylorotwell
Copy link
Member

Why BaseCollection instead of an Eloquent collection? Which one is it? Base collection doesn't have a load method.

@gdebrauwer
Copy link
Contributor Author

ah indeed it should be an eloquent collection

@mstaack
Copy link

mstaack commented May 10, 2023

this broke my scout setup, had to revert to version before.

see: #736

@nemoitis
Copy link

@mstaack Same here. All on a sudden my tests are going red.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants