Laravel Eloquent与JSON和循环

时间:2017-10-09 16:58:49

标签: php json laravel eloquent

我有新闻文章,我想将特定字段传递给JSON。

我试图用这段代码循环播放所有新闻:

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

  }
}

但这会返回一个结果,而不是很多结果。

如果我回显循环,我会用以下代码获得所有需要的结果:

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
    ]);*/

  }
}

如何使用response() - &gt; json()修复此问题,以便获得所有结果?

2 个答案:

答案 0 :(得分:2)

制作一个数组并附加

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

答案 1 :(得分:2)

假设您的实际代码如下所示,最好的方法可能是:

// 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());