BARNOWL
BARNOWL

Reputation: 3589

PHP will not return multiple returns

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

Answers (1)

jeremykenedy
jeremykenedy

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:

  1. Use the $posts variable in the array map instead of making the call again.
  2. Do the actions to each $post in the array map.
  3. Return the $post to the array of $data.
  4. Return the $data.

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

Related Questions