Hi I have the following code to retrieve all posts along with their comments (1 to many relationship)
$posts = Post::with('comments')->get();
Now it works great but my problem is let say I want to do a search on the post title or comment content if given an optional parameter. Something like:
$posts = Post::with('comments');
if (Request::has('query')) {
$posts = $posts->where('content', 'LIKE', '%' . Request::get('query'))->orwhere('title', 'LIKE', '%' . Request::get('query'));
}
$posts = $posts->get();
Now this doesn't work as 'content' column only exists on the comments table. Is there any way do use the where condition on the eager loaded comments relationship?
Use orWhereHas()
and orWhere()
:
$posts = Post::with('comments');
if (request()->has('query')) {
$posts = $posts->orWhereHas('comments', function($q) {
$q->where('content', 'like', '%'.request('query'));
})->orWhere('title', 'like', '%'.request('query'));
}
$posts = $posts->get();
Test it. If you'll want to change behavior, you can use whereHas()
and/or where()
inside if()
construction.