When you do ->get()
, you get an Illuminate\Support\Collection
object back. This object can be returned by the response, since it implements a __toString()
method:
/**
* Convert the collection to its string representation.
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
/**
* Get the collection of items as JSON.
*
* @param int $options
* @return string
*/
public function toJson($options = 0)
{
return json_encode($this->jsonSerialize(), $options);
}
/**
* Convert the object into something JSON serializable.
*
* @return array
*/
public function jsonSerialize()
{
return array_map(function ($value) {
if ($value instanceof JsonSerializable) {
return $value->jsonSerialize();
} elseif ($value instanceof Jsonable) {
return json_decode($value->toJson(), true);
} elseif ($value instanceof Arrayable) {
return $value->toArray();
} else {
return $value;
}
}, $this->items);
}
As you can see, all it does it convert the entire collection to json.
But when you do ->first()
, what happens behind the scenes is that Laravel does ->take(1)->get()->first()
, so that the query is restricted to one row, then a collection containing the result from that one row is retrieved, and finally you get an object back.
So the ->first()
call is made on the collection behind the scenes, meaning you don't get another collection back, but rather a database object - probably of the Illuminate\Database\Query\Builder
kind, I can't quite remember.
And since that class doesn't implement a __toString()
method, the response doesn't know what to do with it. Instead, you get an error.
You can easily simulate the same response by either running json_encode()
on the object, or by returning a json response.