我想运行技能功能,但我做不到。
路由.php
Route::get('setting',function(){
return \App\User::first()->skills();
});
用户.php
protected $casts = [
'skills' => 'json'
];
public function skills(){
return new Skills($this , $this->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;
}
}
我想进入/settings 页面我有“The Response content must be a string or object implementing __toString(), "object"given.
”错误。
我试图在路由中添加 dd()
函数的返回值,我看到了所有 JSON 数据,但 $skills->get()
, $skill-> set()
当时没有工作。
编辑:
技能.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ı");
}
}
最佳答案
当你做的时候
return \App\User::first()->skills();
您返回的是 Relation 定义对象,它没有实现 __toString() 方法。返回相关对象所需的是
return \App\User::first()->skills;
这将返回一个包含相关技能的Collection对象——这将被正确序列化。
关于php - Laravel 的 Response 内容必须是字符串或对象实现 __toString(), "object"given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31771276/