【问题标题】:Laravel Eloquent with JSON and looping带有 JSON 和循环的 Laravel Eloquent
【发布时间】:2018-03-20 23:02:41
【问题描述】:

我有新闻文章,我想将特定字段传递给 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()->json() 来解决这个问题,这样我才能得到所有的结果?

【问题讨论】:

    标签: php json laravel eloquent


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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);
      }
      

      【讨论】:

        猜你喜欢
        • 2017-05-20
        • 2021-04-27
        • 2014-11-23
        • 2016-09-12
        • 2013-05-20
        • 1970-01-01
        • 1970-01-01
        • 2018-12-21
        • 2016-06-30
        相关资源
        最近更新 更多