Laravel The content of the response must be a string or an object that implements __toString (), the "object" given

I want to run the Skills function, but I cannot.

Route.php

Route::get('setting',function(){ return \App\User::first()->skills(); }); 

User.php

 protected $casts = [ 'skills' => 'json' ]; public function skills(){ return new Skills($this , $this->skills); } 

Skills.php

 namespace App; use App\User; use Mockery\Exception; class Skills { protected $user; protected $skills = []; public function __construct(User $user,array $skills){ $this->user=$user; $this->skills=$skills; } } 

I want to enter / set the page. I have the error " The Response content must be a string or object implementing __toString(), "object" given. ".

I tried to add the dd() return function to the route, I see all the JSON data, but $skills->get() , $skill->set() did not work at that time.

Edit:

Skills.php

 <?php /** * Created by PhpStorm. * User: root * Date: 01.08.2015 * Time: 11:45 */ namespace App; use App\User; use Mockery\Exception; class Skills { protected $user; protected $skills = []; public function __construct(User $user,array $skills){ $this->user=$user; $this->skills=$skills; } public function get($key){ return array_get($this->skills,$key); } public function set($key,$value){ $this->skills[$key]=$value; return $this->duration(); } public function has($key){ return array_key_exists($key,$this->skills); } public function all(){ return $this->skills; } public function merge(array $attributes){ $this->skills = array_merge( $this->skills, array_only( $attributes, array_keys($this->skills) ) ); return $this->duration(); } public function duration(){ return $this->user->update(['skills' => $this->skills]); } public function __get($key){ if ($this->has($key)) { return $this->get($key); } throw new Exception("{$key} adlı Yetenek bulunamadı"); } } 
+8
json php laravel laravel-5 laravel-4
source share
3 answers

When you do

 return \App\User::first()->skills(); 

you are returning a Relation definition object that does not implement the __ toString () method. To return the related object you need

 return \App\User::first()->skills; 

This will return the Collection properties associated with the binding to the objects - this will be correctly serialized.

+6
source share

Maybe you can go with get_object_vars($skills) and later loop through object variables. Example:

 foreach(get_object_vars($skills) as $prop => $val){ } 
+1
source share

in Route.php , return such a collection

 Route::get('setting',function(){ return \App\User::first()->skills; }); 

OR

 Route::get('setting',function(){ $skills = \App\User::first(['id','skills']); return $skills->skills; }); 

And on your User.php model, you can indicate that your code says so

 protected $casts = [ 'skills' => 'json' ]; public function skills() { return $this->skills; } 

I hope this helps someone.

0
source share

All Articles