Reputation: 41
I use Laravel.
I have relationship between post and comments.
I have $post
and I'd like to get related $comments
only with value published
set to true
.
In controller I have:
$post = Post::find($id);
$comments = $post->comments->where('published', 1)->get();
And here variable comments
looks properly, but when I do:
return [
'comments' => $comments,
'post' => $post,
];
I have all comments from db and post connecting with comments in one array. e.g
$post:
id 24
title "lorem"
body "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis explicabo molestias obcaecati placeat vero. Alias aliquid consectetur, deserunt ducimus iure magnam minus molestias neque pariatur quidem sint temporibus totam vitae."
user_id 2
published 1
created_at "2018-12-03 12:14:30"
updated_at "2019-03-29 10:08:26"
comments [
1 [ ... ]
2 [ ... ]
n [ ... ]
]
$comments {
1 [ ... ]
2 [ ... ]
n [ ... ]
}
So where did I make a mistake? Why does it change?
model Comment.php
public function post()
{
return $this->belongsTo(Post::class);
}
public function scopePublished($query)
{
return $query->where('published', 1);
}
Post.php
public function comments()
{
return $this->hasMany(Comment::class);
}
Upvotes: 0
Views: 44
Reputation: 1763
Try this
$post = Post::with(['comments' => function($q) {
$q->where('published', 1); // or $q->published();
}])
->find($id);
You can read Where with relationship
In blade file, you can get post and comments using
{{ dd($post) }} //get post
{{ dd($post->comments) }} //get post related commnets
Upvotes: 1
Reputation: 2780
$comments = $post->comments->where('published', 1)->get();
checks for posts that have published set as 1. To get published comments for any post, add a new relationship in your Post.php as follows :
public function publishedComments()
{
return $this->comments()->where('published', 1);
}
You can then use it in your controller like so
$comments = $post->publishedComments()->get();
Upvotes: 0