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?
from Laravel Questions and Answers https://laravelquestions.com/php/in-laravelhow-can-i-use-foreach-loop/
via Lzo Media
No comments:
Post a Comment