【问题标题】:Method App\Follower::__toString() must not throw an exception: Error方法 App\Follower::__toString() 不得抛出异常:错误
【发布时间】:2019-05-12 18:04:52
【问题描述】:

我正在 laravel 中制作一个追随者用户控制器。

我的控制器有以下功能:

public function follow($id)
{
    if (Auth::user()) {
        $follower = Auth::user()->user_id;
        $user_to_follow = User::Find($id);
        if ($user_to_follow) {
            $follower = new Follower;
            $follower->follower_id = $follower;
            $follower->user_id = $user_to_follow;
            if ($follower->save()) {           <-- receiving error here
                return "done";
            } else {
                return redirect('/')->back();
            }
        }
        return $follower;
    } 
}

追随者型号:

 protected $table = "followers";

protected $fillable = ['follower_id', 'user_id', 'accepted'];

public function user()
{
    return $this->belongsTo('App\User', 'user_id');
}

用户模型

public function followers()
{
    return $this->hasMany('App\Follower', 'user_id');
}

在视图中

<a href="/follow/2">Follow</a>

点击关注我收到错误,

方法 App\Follower::__toString() 不能抛出异常,被捕获 Illuminate\Database\Eloquent\JsonEncodingException:错误编码 带有 ID [] 的模型 [App\Follower] 到 JSON:检测到递归

谁能解释这个错误是什么以及如何消除它? 提前谢谢你..

【问题讨论】:

  • 您能否展示您的完整模型定义,以确保其中没有其他隐藏内容?
  • @aynber 追随者模型就是这样......并且用户模型与其他模型有关系并且受保护 $table = "users";受保护的 $primaryKey = "user_id"; protected $fillable = ['user_name', 'email', 'password', 'tag_id', ]; protected $hidden = ['密码', 'remember_token', ];

标签: php laravel eloquent


【解决方案1】:

问题很明显,您对 2 个不同的事物使用相同的变量。首先你要做:

$follower = Auth::user()->user_id;

但后来你会这样做

$follower = new Follower;

所以现在当你使用时:

$follower->follower_id = $follower;

然后您尝试将相同的对象分配给对象属性,并且可能在保存时导致问题。

你应该做的是改变:

$follower = Auth::user()->user_id;

进入

$followerId = Auth::user()->user_id;

然后

$follower->follower_id = $follower;

进入

$follower->follower_id = $followerId;

【讨论】:

  • 大声笑是的...我没有意识到这一点。多么愚蠢的错误,我一直在努力。谢谢你的帮助
猜你喜欢
  • 2015-04-04
  • 2017-09-09
  • 2014-04-20
  • 2014-12-19
  • 2021-08-03
  • 1970-01-01
  • 2021-03-09
  • 2021-07-09
  • 2014-11-18
相关资源
最近更新 更多