N
N
Nikolay2018-07-11 13:18:50
Laravel
Nikolay, 2018-07-11 13:18:50

How does Laravel return multiple objects per request?

Hello!
I make a request to the simplest API, which should return three values.
If the controller uses
return Set::with('items')->get();
Then three collections come as saysalert();

[object object], [object object], [object object]

And if I make a request where I change the keys:
return Set::with('items')->get()->mapWithKeys(function ($item) { return [$item->id => $item]; });

Thenalert(); it says that an object with collections has returned:
[object object]

(that is, an object that contains three collections)
What is remarkable, if you display this data on the page with dd()- Visually, the data looks and is located the same.
How does it work? And can I also return several objects in the second case, as it happened in the first?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hOtRush, 2018-07-11
@hOtRush

1. Read the JSON spec
2. Stop debugging alerts in 2018
[{}, {}, {}]
and
{"0": {}, "1": {}, "2": {}}
are slightly different things

Y
Yan-s, 2018-07-11
@Yan-s

Something you misunderstand about JSON.
You receive 1 array of objects, in which there are 3 objects. This is not much different from the second situation.
To understand why, see the example: sandbox.onlinephpfunctions.com/code/342145de51348c...

example code
$ar = [0 => 0, 1 => 1, 2 => 2];
$ar2 = [1 => 1, 0 => 0, 2 => 2];

var_dump(json_encode($ar));
var_dump(json_encode($ar2));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question