skip to Main Content

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]);
}

Sort comments by active

2

Answers


  1. Read docs https://laravel.com/docs/10.x/eloquent-relationships!

    First of all, you have Post type filtered as $post. Just add other thing dynamically to that and finally fetch the result. You don’t have to find it again!

    public function show(Post $post)
    {
        $post_res = $post->with(['comments' => function($query) {
            $query->orderBy('status', 'asc');
        }])->get();
    
        return view('post.show', ['post' => $post_res]);
    }
    

    If your function in controller just accepts ID as argument, you simply can change your code to:

    public function show(int $post_id)
    {
        $post_res = Post::find($post_id)->with(['comments' => function($query) {
              $query->orderBy('status', 'asc');
          }])->get();
    
        return view('post.show', ['post' => $post_res]);
    }
    
    Login or Signup to reply.
  2. Use whereHas(),

    $post = Post::with('comments')->whereHas('comments', function ($q) {
              $q->where('status', 'active');
            })
    ->find($post);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search