Alameddin Çelik Alameddin Çelik - 1 month ago 13
JSON Question

Laravel The Response content must be a string or object implementing __toString(), "object" given

I want to run Skills function but I cant it.

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 /settings page I have "
The Response content must be a string or object implementing __toString(), "object" given.
" error.
I tried to add dd() function's return in route,I see all json data but $skills->get(), $skill->set() didn't working at the time.

I cant speak english goodly, Im sorry

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ı");
}


}

Answer

When you do

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

you are returning the Relation definition object, which doesn't implement __toString() method. What you need in order to return the related object is

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

This will return a Collection object cotaining related skills - this will be properly serialized.