Search code examples
phplaravellaravel-5.5

Laravel Get data One to Many Relationship with conditions


how to display data one too many relationships with conditions into view.

I have a blog post that has a comment, but this comment has a condition that published or not.

here my Post Model

...

public function comments()
{
    return $this->hasMany(Comment::class);
}
...

on my code above I can simply use $post->comments to show all the comments.

like I said before, I need only show comments with published is true

but how to add conditions?...


Solution

  • You can achieve this by getting the post with it's published comments;

    $post = Post::where('id', $id)->with('comments', function ($q) { 
         $q->where('published', true);
    })->first(); 
    

    Then when in the view you call $post->comments, you will only get the published one.

    Alternatively, if you really want to you can update your Model to have a published comments relationship, but this is less advised.

    public function publishedComments()
    {
        return $this->hasMany(Comment::class)->where('published', true);
    }