如何修改 Eloquent 关系并将其传递给 Blade

我需要修改 Eloquent 关系(它可以改变值,或洗牌,或删除某些项目)


在控制器中,您可以这样做:


$question = Question::first();

//$question has a relationship with Answer, therefore I have $question->answers.

$question->answers = $this->modifyAnswers($question->answers);

dd($question->answers) //Worked! Displaying modified Answers


return view('someView', compact($question));

//In the blade file, it's receiving original $question->answers

解决方法是添加具有不同名称的新属性。


$question->modifiedAnswers = $this->modifyAnswers($question->answers);

//And blade can access $question->modifiedAnswers

但是有什么方法可以让我在不添加其他属性的情况下修改值?


蛊毒传说
浏览 134回答 1
1回答

HUH函数

你可以,用这个方法 setRelation($name, $value)$question = Question::first();$question->setRelation('answers', $this->modifyAnswers($answers));dd($question->relationLoaded('answers'));更多信息在这里文档
打开App,查看更多内容
随时随地看视频慕课网APP