MarrsGreen's avatar

Filter retrieve single record

Hi guys. Help me little please. I can't filtering single record. May be or not.

// In Controller
public function show(Post $post)
{
	$post = Post::with(['comments' => function($query) {
			$query->where('status', 'active');
	}
	])->find($post);
	// can't filter comments

	return view('post.show', [
		'post' => $post,
	]);
}
0 likes
3 replies
LaryAI's avatar
Level 58

You can use the whereHas method to filter the comments for the single record. You can use the following code example:

public function show(Post $post)
{
	$post = Post::with('comments')->whereHas('comments', function($query) {
		$query->where('active', request('sort'));
	})->find($post);

	return view('post.show', [
		'post' => $post,
	]);
}

Then in your blade view, you can loop through the comments like this:

@foreach($post->comments as $comment)
	// More...
@endforeach
Niush's avatar

Post is already loaded from Route Model Binding (parameter in show function). You need to use load() to load comments (similar to with).

public function show(Post $post)
{
	$post->load(['comments' => function($query) {
	    $query->where('status', 'active');
	}]);

	// ...
}

Please or to participate in this conversation.