Adding two arrays to Laravel get () Query Builders
I have questions in Laravel. First, to get one post. Second, to get all the comments. My problem is that I cannot correctly add the two output arrays get()
to Laravel Query Builders.
When I tried to join them, the post popped up 3 times as I have 3 comments for this post. So instead of joining, I tried array_push
them. The result now looks like this.
[
{
"id": 44,
"image": "9178hello.jpg",
"description": "Lorem ipsum dolor sit amit!",
"address": "internet",
"lat": 45.435,
"long": 2312.3,
"created_at": "1 hour ago"
},
[
{
"comment": "my comment.... my comment 1.....",
"created_at": "2015-01-11 17:24:27"
},
{
"comment": "my comment.... my comment 2.....",
"created_at": "2015-01-11 17:24:29"
},
{
"comment": "my comment.... my comment 3.....",
"created_at": "2015-01-11 17:24:30"
}
]
]
How can I do it like:
[
{
"id": 44,
"image": "9178hello.jpg",
"description": "Lorem ipsum dolor sit amit!",
"address": "internet",
"lat": 45.435,
"long": 2312.3,
"created_at": "1 hour ago",
"comments" : {
list all the comments here...
}
}
]
Here Request:
$disaster = Disaster::where('name', '=', $name)->first(['id']);
$post = DB::table('posts')
->join('locations', 'locations.id', '=', 'posts.location')
->join('users', 'users.id', '=', 'posts.user_id')
->select('posts.id', 'posts.image', 'posts.description', 'locations.address', 'locations.lat', 'locations.long', 'posts.user_id', 'users.firstname', 'users.lastname', 'posts.created_at')
->where('posts.disaster_id', '=', $disaster->id)
->where('posts.id', '=', $id)
->get();
if (empty($post)) {
return ['error' => 'no post found'];
}
$post[0]->created_at = Carbon::parse($post[0]->created_at)->diffForHumans();
$comments = DB::table('comments')
->select('comment', 'created_at')
->where('post_id', '=', $post[0]->id)
->get();
array_push($post, $comments);
return $post;
source to share
You can do it
$array = array_merge($post, array('comments' => $comments));
Docs: array_merge
This will add a comment to the comments key
post array.
Since you are using Laravel, why not use the Bad relationship ? Just do one-many post-comment relationships and get them the way you want.
Read Laravel Briefs
source to share