Dicky Raambo
Dicky Raambo

Reputation: 523

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?...

Upvotes: 0

Views: 1196

Answers (2)

Simon R
Simon R

Reputation: 3772

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

Upvotes: 1

Daniel
Daniel

Reputation: 1041

You can get only published comments by using
$this->post->comments()->where('published', true)->get()

Check the Documentation

Of course, since all relationships also serve as query builders, you can add further constraints to which comments are retrieved by calling the comments method and continuing to chain conditions onto the query: $comment = App\Post::find(1)->comments()->where('title', 'foo')->first();

Upvotes: 1

Related Questions