Laravel Response内容必须是实现__toString()," object"的字符串或对象。给定的

时间:2015-08-02 11:11:14

标签: php json laravel laravel-4 laravel-5

我想运行技能功能,但我不能。

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;
    }
}

我想进入/设置页面我有" The Response content must be a string or object implementing __toString(), "object" given."错误。

我尝试在路由中添加dd()函数返回,我看到所有JSON数据,但$skills->get()$skill->set()当时没有工作。

编辑:

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

3 个答案:

答案 0 :(得分:6)

当你这样做时

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

您将返回Relation定义对象,该对象未实现 __ toString()方法。返回相关对象需要的是

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

这将返回一个集合对象,其中包含相关技能 - 这将被正确序列化。

答案 1 :(得分:1)

您可以通过对象变量使用get_object_vars($skills)和更晚的loop。 例如:

foreach(get_object_vars($skills) as $prop => $val){
}

答案 2 :(得分:0)

Route.php 中,返回一个类似的集合

2.2.31 (Unix)

OR

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

在您的User.php模型中,您可以将您的代码视为如此

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

我希望这有助于某人。