Reputation: 31
I have news articles and I want to pass specific fields to a JSON.
I've tried to loop all the news with this code:
public function appNews() {
$news = News::orderBy('id', 'desc')->get();
foreach($news as $newsOne) {
$title = $newsOne->title;
$body = $newsOne->body;
$image = $newsOne->image;
return response()->json([
'title' => $title,
'body' => $body,
'image' => $image
]);
}
}
But this returns one result instead of many.
If I echo the loop I get all the needed results with this code:
public function appNews() {
$news = News::orderBy('id', 'desc')->get();
foreach($news as $newsOne) {
$title = $newsOne->title;
$body = strip_tags($newsOne->body);
$image = $newsOne->image;
echo '<div>' . $newsOne->title . '</div>';
/*return response()->json([
'title' => $title,
'body' => $body,
'image' => $image
]);*/
}
}
How can I fix that with response()->json(), so I can get all the results?
Upvotes: 1
Views: 150
Reputation: 111829
Assuming your actual code looks like this, the best way would be probably:
// here you select only fields you need
$news = News::select('title', 'body', 'image')->orderBy('id', 'desc')->get();
// here you return changed content of body by striping tags
return response()->json($news->map(function($singleNews) {
$singleNews->body = strip_tags($singleNews->body);
return $singleNews;
})->all());
Upvotes: 2
Reputation: 9117
make one array and append it
public function appNews() {
$news = News::orderBy('id', 'desc')->get();
$array = [];
foreach($news as $newsOne) {
$title = $newsOne->title;
$body = strip_tags($newsOne->body);
$image = $newsOne->image;
$array[] = [
'title' => $title,
'body' => $body,
'image' => $image
];
}
return response()->json($array);
}
Upvotes: 2