LucasAlfson's avatar

Enhance Eloquent search for a Model which has two relations

Hi, I want to search a keyword in a main model an its two relations, I wrote an Eloquent query, but I'm not sure about it, it works fine, but here, the response time is important for me, now, I just have a small database, but it may be huge. In the code below, at first I get the posts of a city, then I search a keyword in the posts and also in the comments and in another related table, which I call it, notes.

    $posts = current_city()->posts()
        ->where(function ($query) use ($keyword) {
            foreach ($this->posts_searchable_columns as $column) {
                $query->orWhere('posts.' . $column, 'LIKE', '%' . $keyword . '%')
                    ->orWhereHas('comments', function ($query) use ($keyword) {
                        $query->where(function ($query) use ($keyword) {
                            foreach ($this->comments_searchable_columns as $column) {
                                $query->orWhere('comments.' . $column, 'LIKE', '%' . $keyword . '%');
                            }
                        });
                    })
                    ->orWhereHas('note', function ($query) use ($keyword) {
                        $query->where(function ($query) use ($keyword) {
                            foreach ($this->notes_searchable_columns as $column) {
                                $query->orWhere('notes.' . $column, 'LIKE', '%' . $keyword . '%');
                            }
                        });
                    });
            }
        });

Is the code above optimized enough or could be better?

  • I don't want to use Scout.
0 likes
1 reply
Snapey's avatar

looks to me like you might be doing all this with an in memory collection ... which wont be scalable

Install Laravel debugbar so you can see models, queries and memory footprint

Please or to participate in this conversation.