我正在调用此控制器来更新模型:
public function update(Request $request, $id)
{
$question = Question::find($id);
$this->authorize('edit', $question); // uses Laravel's built-in Policy framework
$updateArray = [
'question' => $request->question,
'type_based_id' => $request->type_based_id,
];
//$question = Question::where('id', $id);
$question = $question->update($updateArray);
// Add the id into the array for return to the client
$updateArray["id"] = $id;
return ['message' => 'Question Updated', 'data' => $updateArray];
}
上面的代码在调用$question->update()
时抛出一个MassAssignmentException。如果我取消注释$question = Question::where('id', $id);
它的工作原理。
我做了一些日志记录,似乎find()返回我的模型的实例(App\Question
)和where()返回一个构建器(Illuminate\Database\Eloquent\Builder
)
如何在不进行两次单独的数据库请求的情况下同时满足authorize()和update()?
谢谢!
它使用查询生成器的原因是因为它绕过了模型的质量分配检查。您正在运行自己的查询而不使用Model的更新方法。
问题:: where() - > update在Query Builder上调用update,而不是Model。
当您已经拥有要更新的模型实例时,没有理由使用查询构建器,但实际上并没有运行任何其他SQL查询。
MassAssignmentException通常表示您传递的属性之一在模型中受到保护。对于unguard属性,要么从$guarded
属性中删除它们,要么将它们添加到模型的$fillable
属性中。不要同时使用$ guarded和$ fillable,你必须使用其中一个。阅读完整的文档:
MassAssigntmentException
是由于你正在更新的字段不是fillable
而因此被保护免于任务,要实现这一点,你需要在Question
类上设置这些。
public class Question
{
protected $fillable = [
'question',
'type_based_id',
];
}