DEV Community

Peter Fox
Peter Fox

Posted on • Originally published at Medium on

Laravel Scout: Eager loading models for indexing


Photo by Maksym Kaharlytskyi on Unsplash

If you’re like me you want to get eager loading right from day one. One area that can initially seem difficult for this is when it comes to index models with Laravel Scout.

This can be a real problem if you’re using relational attributes in your indexes. For example, imagine we have a Post model that we wish to index with information about the person who created the Post.

class Post extends Model
{
    public function toSearchableArray(): array
    {
        return [
            'id' => $this->id,
            'content' => $this->content,
            'created_by' => $this->user->name,
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

If we try to reindex the Post mode with this code we will end up with N+1 issues because the user will be loaded per Post method.

Luckily there is a method for being able to do this.

Implement MakeSearchableUsing

Using the method makeSearchableUsing we can take the collection of models to be indexed and we can then use the eager load functionality to make use the users are loaded.

use Illuminate\Database\Eloquent\Collection;

class Post extends Model
{
    public function toSearchableArray(): array
    {
        return [
            'id' => $this->id,
            'content' => $this->content,
            'comments_count' => $this->comment_count,
            'created_by' => $this->user->name,
        ];
    }

    public function makeSearchableUsing(Collection $models): Collection
    {
        return $models->load('user')->loadCount('comments');
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Often Laravel will have what you need. In the case of Laravel Scout, the documentation can be difficult to follow. While this feature is documented and mentions eager loading it can be difficult to find. It’s worth taking a deep dive into the source code and understanding what can and can’t be extended through models.

I’m Peter Fox, a software developer in the UK who works with Laravel. Thank you for reading my article, I’ve got several more available at https://articles.peterfox.me. I’m also now Sponsorable on GitHub. If you’d like to encourage me to write more articles like this please do consider dropping a small one-off donation.

Top comments (0)