Well if you want everything including non-associative arrays like on a Collection or empty to return {} then this:
->toJson(JSON_FORCE_OBJECT);
Hell there,
By default laravel returns JSONArray but I want JSONObject. I tried to use toJson() but it doesn't work.
Any help ?
@absiddiqueLive The Model/Collections will use toJson() by default when __toString() is tried so no need to do that.
public function __toString()
{
return $this->toJson();
}
So this is the same.
return User::with('roles')->first();
return User::find(1);
return User::all();
This also doesn't make sense to do.
return Response::json(User::all()->toArray());
as when you try and use a Collection as a string it does toArray behind the scenes for you.
public function toJson($options = 0)
{
return json_encode($this->toArray(), $options);
}
so if he wanted a json array he would just do return User::all(); like above
he's also wanting the array as an object though, and would also mean the Response::json() couldn't also be used to set the header as it would be like doing the encode twice and the quotes being escaped.
json_encode(json_encode( $array, JSON_FORCE_OBJECT))
Please or to participate in this conversation.