我试图渲染多个回报,渲染两个回报的最佳方法是什么。
其中一个返回可删除的收集,可更新的收不到。
public function getPosts()
{
$posts = Post::with('user')->get();
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
return response()->json(Post::with('user')->get()->map(function(Post $post){
return collect($post->toArray())->put('deletable', auth()->user()->can('delete', $post));
return collect($post->toArray())->put('update', auth()->user()->can('update', $post));
}));
}
已更新,帖子似乎没有显示以下内容:
public function getPosts()
{
$posts = collect(Post::with('user')->get());
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
$data = $posts->map(function(Post $post)
{
$post->toArray()->put('deletable', auth()->user()->can('delete', $post));
$post->toArray()->put('update', auth()->user()->can('update', $post));
return $post;
});
return response()->json($data);
}
答案 0 :(得分:2)
尝试以下方面的内容:
public function getPosts()
{
$posts = Post::with('user')->get();
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
$data = $posts->map(function(Post $post)
{
$post->toArray())->put('deletable', auth()->user()->can('delete', $post);
$post->toArray())->put('update', auth()->user()->can('update', $post);
return $post;
});
return response()->json($data);
}
这是怎么回事:
以下是数组地图上的文档并返回。
您不能多次返回。
阅读以下内容:
https://laravel.com/docs/5.5/collections#method-map
http://php.net/manual/en/function.return.php
更新
试试这个:
public function getPosts()
{
$posts = Post::with('user')->get();
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
$data = $posts->map(function(Post $post)
{
$user = auth()->user();
if($user->can('delete', $post)) {
$post['deletable'] = true;
}
if($user->can('update', $post)) {
$post['update'] = true;
}
return $post;
})
return response()->json($data);
}