简体   繁体   中英

In laravel,how can I use foreach loop?

When I use this code:

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

Output is:

[
    {
        "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
    }
]

But when I use foreach loop it shows only one of the array

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

And the output for this code is:

Eloquent Basic Insert

How can I show all the title of the array on browser? and what is wrong on my code?

What you are doing is returning the title at the first loop. You need to put your return out of your foreach :

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

Just replace the return word by echo and it will be work fine

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

Just for something different, you should be able to do something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM