Avijit Biswas
Avijit Biswas

Reputation: 51

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?

Upvotes: 0

Views: 349

Answers (3)

ali
ali

Reputation: 862

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

Upvotes: 2

martincarlin87
martincarlin87

Reputation: 11042

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

Upvotes: 1

Fanie Void
Fanie Void

Reputation: 329

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

Upvotes: 5

Related Questions