In the following very simplified example and study case, we get the list of posts and the count of comments for each post.
However, I intended to send to client side only the value, i.e. 2, and not the array object [{total: 2}]
Is there a simplified way to do this with the laravel?
Note: DB::select must be used
public function readPosts(Request $request) {
$posts = DB::select("SELECT * FROM posts");
foreach ($posts as $key => $post) {
$idComment = $post->id_comment;
$post->nComments = DB::select('SELECT COUNT(id_comment) As total FROM post_comments WHERE id_comment = ? ', [$idComment]);
}
if($posts){
return response()->json(['success'=>true, "output"=>$posts);
}else{
return response()->json(['success'=>false]);
}
}
response
data:
0:
id_post: 1
post: "post text"
nComments: [{total:2}]
1:
id_post: 2
post: "post text 2"
nComments: [{total:1}]
Expected
data:
0:
id_post: 1
post: "post text"
nComments: 2
1:
id_post: 2
post: "post text 2"
nComments: 1
comments()in the Post model or you need help with that ?