在laravel中,我如何使用foreach循环?

时间:2018-05-15 15:40:01

标签: php laravel foreach

当我使用此代码时:

Route::get('/user/{id}/posts', function ($id){
   $post = User::find($id)->postst;
   return $post;
});

输出是:

[
    {
        "id":1,
        "user_id":1,
        "title":"Eloquent Basic Insert",
        "content":"By eloquent we can easily insert a data and it is awesome",
        "created_at":"2018-05-15 14:45:34",
        "updated_at":"2018-05-15 14:45:34",
        "deleted_at":null
    },
    {
        "id":2,
        "user_id":1,
        "title":"Add with create",
        "content":"This might be fail",
        "created_at":"2018-05-15 14:47:59",
        "updated_at":"2018-05-15 14:47:59",
        "deleted_at":null
    }
]

但是当我使用foreach循环时,它只显示一个数组

 Route::get('/user/{id}/posts', function ($id){
   $post = User::find($id)->postst;
   foreach ($post as $post){
       return $post->title. '<br>';
   }
});

此代码的输出为:

Eloquent Basic Insert

如何在浏览器上显示数组的所有标题?我的代码有什么问题?

3 个答案:

答案 0 :(得分:4)

您正在做的是在第一个循环返回标题。 您需要将returnforeach

中删除
Route::get('/user/{id}/posts', function ($id){
   $post = User::find($id)->postst;
   $titles = "";
   foreach ($post as $post){
       $titles .= $post->title. '<br>';
   }
   return $titles;
});

答案 1 :(得分:1)

只是为了不同的东西,你应该能够做到这样的事情:

Route::get('/user/{id}/posts', function ($id){
    $posts = User::with('posts')->find($id)->posts;
    return $posts->pluck('title');
});

答案 2 :(得分:1)

只需用echo替换返回单词,它就可以正常工作

 Route::get('/user/{id}/posts', function ($id){
 $post = User::find($id)->postst;
  foreach ($post as $post){
   echo $post->title. '<br>';
  }
});