php - Laravel DB : first() method brings the Response content must be a string -


i use laravel illuminate , error when use first() method single result:

the response content must string or object implementing __tostring(), "object" given.

return db::table('todos')->where("title","your list")->first(); 

if select get() method works:

return db::table('todos')->where("title","your list")->get(); 

do know what's wrong first statement?

when ->get(), illuminate\support\collection object back. object can returned response, since implements __tostring() method:

/**  * convert collection string representation.  *  * @return string  */ public function __tostring() {     return $this->tojson(); }  /**  * collection of items json.  *  * @param  int  $options  * @return string  */ public function tojson($options = 0) {     return json_encode($this->jsonserialize(), $options); }  /**  * convert object 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 can see, convert entire collection json.

but when ->first(), happens behind scenes laravel ->take(1)->get()->first(), query restricted 1 row, collection containing result 1 row retrieved, , object back.

so ->first() call made on collection behind scenes, meaning don't collection back, rather database object - of illuminate\database\query\builder kind, can't quite remember.

and since class doesn't implement __tostring() method, response doesn't know it. instead, error.

you can simulate same response either running json_encode() on object, or returning json response.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -