mdev11's avatar

Eloquent toJson() set key

This command:

User::get()->toJson();

returns:

[{"id":1,"name":"John"},{"id":2,"name":"Doe"}]

Is it possible to set a key for the response to check with js?

Like:

{"users":[{"id":1,"name":"John"},{"id":2,"name":"Doe"}]}

Alternative to:

$users = User::get();
return response()->json(['users', $users);
0 likes
3 replies
tisuchi's avatar

@mdev11 You can try this:

$users = User::get();
return $users->toJson(JSON_PRETTY_PRINT, 'users');

Or

return response()->json([
	'users' => User::get()
]);
enoch91's avatar

You can either do this

$users = User::get();
return json_encode(['users' => $users]);

or

return response()->json(['users' => User::get()]);

Please or to participate in this conversation.