Reputation: 3589
I'm trying to render out multiple returns, what is the best way of rendering both returns.
One of them returns which is the deleteable collect, the updatable doesn't return.
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));
}));
}
updated, posts don't appear doing the following:
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);
}
Upvotes: 1
Views: 55
Reputation: 4285
Try something along the lines of :
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);
}
Whats going on here:
Here are the docs on array maps and return.
You CANNOT return more than once.
Read these:
https://laravel.com/docs/5.5/collections#method-map
http://php.net/manual/en/function.return.php
Update:
Try this:
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);
}
Upvotes: 2