当我使用这个代码时:
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>';
}
});该代码的输出是:
雄辩的基本插入
如何在浏览器上显示数组的所有标题?我的密码怎么了?
发布于 2018-05-15 15:46:57
您要做的是在第一个循环中返回标题。你需要把你的return从你的foreach中拿出来
Route::get('/user/{id}/posts', function ($id){
$post = User::find($id)->postst;
$titles = "";
foreach ($post as $post){
$titles .= $post->title. '<br>';
}
return $titles;
});发布于 2018-05-15 16:30:45
只要用echo替换返回的单词,它就会工作得很好。
Route::get('/user/{id}/posts', function ($id){
$post = User::find($id)->postst;
foreach ($post as $post){
echo $post->title. '<br>';
}
});发布于 2018-05-15 15:54:40
只是为了做一些不同的事情,你应该能够做这样的事情:
Route::get('/user/{id}/posts', function ($id){
$posts = User::with('posts')->find($id)->posts;
return $posts->pluck('title');
});https://stackoverflow.com/questions/50354242
复制相似问题