laminatefish
laminatefish

Reputation: 5246

Laravel 5 response()->json always returns an array?

Is there any way to stop laravel always returning an array, regardless if there is only a single element? I've checked the docs and come up short. It's fine if thats just the way it is of course, just seems a little silly, as you wouldn't post an array to an endpoint, if there was only one element!

Return payload for sanity sake:

[
    {
        "id": 1,
        "created_at": "2015-05-22 15:41:24",
        "updated_at": "2015-05-22 15:41:24",
        "deleted_at": null,
        "closed_loop_interaction_type_id": 1,
        "interaction_note": "Test Interaction note",
        "closed_loop_processes_id": 1,
        "interaction_type": {
            "id": 1,
            "created_at": "2015-05-22 15:41:24",
            "updated_at": "2015-05-22 15:41:24",
            "deleted_at": null,
            "type": 0,
            "method": "Phone Call (mobile)"
        }
    }
]

That's one object, but sent back as an array of 1. Is there a way to stop this? Is it the way I'm populating models?

$query = ClosedLoopInteraction::with('interactionType');
// Construct a list of headers
$headers = \HeaderHelper::generatePaginationHeader($page, $query, 'closedloop', $limit);
\QueryHelper::handleQueryFiltering(
    $query, ['limit'=> $limit, 'page' => $page]);
$response = response()->json($query->get(), \ApiResponse::$STATUS_OK);
// Add the constructed headers to the response
\HeaderHelper::addHeadersToResponse($response, $headers);
return $response;

Upvotes: 3

Views: 1321

Answers (3)

Pawel Bieszczad
Pawel Bieszczad

Reputation: 13325

It depends. Looking at your code you are returning a list of models. If thats the case you should also return an array, be it empty, single or many models. That way the return type is always the same and easier to process. However if you viewing a specific model, editing or something, use the method first() suggested by another answer.

Upvotes: 1

taxicala
taxicala

Reputation: 21759

Well, Laravel, from behind, is using json_encode in order to return the JSON you are seeing, having this on hand, you can know that when you pass an array, no matter the length, even length === 1, you will get an output as an array, because thats the way json_encode works, so you should do as @Mark Baker says, and modify the following line:

$response = response()->json($query->get(), \ApiResponse::$STATUS_OK);

To:

$response = response()->json($query->first(), \ApiResponse::$STATUS_OK);

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212402

Use the Query first() method rather than the get() method

Upvotes: 6

Related Questions