如何授权然后更新 Laravel 模型
How to authorize then update a Laravel model
我正在调用此控制器来更新模型:
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() returns 是我的模型实例 (App\Question
) 和 where() returns 构建器 (Illuminate\Database\Eloquent\Builder
)
如何在不发出两个单独的数据库请求的情况下同时满足 authorize() 和 update()?
谢谢!
它使用查询生成器工作的原因是因为它绕过了模型的质量分配检查。您是 运行 您自己的查询,没有使用模型的更新方法。
Question::where()->update 正在查询生成器上调用更新,而不是模型。
当您已经拥有正在更新的模型实例时,没有理由使用查询构建器,但这实际上并不是 运行 任何额外的 SQL 查询。
MassAssignmentException 通常意味着您传递的属性之一在模型中受到保护。要取消保护属性,请将它们从 $guarded
属性 中删除或将它们添加到模型的 $fillable
属性 中。不要同时使用 $guarded 和 $fillable,您必须使用其中之一。在此处阅读完整文档:
MassAssigntmentException
是由于您正在更新的字段不是 fillable
并且因此被保护免受分配,为此您需要在 Question
class.
public class Question
{
protected $fillable = [
'question',
'type_based_id',
];
}
我正在调用此控制器来更新模型:
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() returns 是我的模型实例 (App\Question
) 和 where() returns 构建器 (Illuminate\Database\Eloquent\Builder
)
如何在不发出两个单独的数据库请求的情况下同时满足 authorize() 和 update()?
谢谢!
它使用查询生成器工作的原因是因为它绕过了模型的质量分配检查。您是 运行 您自己的查询,没有使用模型的更新方法。
Question::where()->update 正在查询生成器上调用更新,而不是模型。
当您已经拥有正在更新的模型实例时,没有理由使用查询构建器,但这实际上并不是 运行 任何额外的 SQL 查询。
MassAssignmentException 通常意味着您传递的属性之一在模型中受到保护。要取消保护属性,请将它们从 $guarded
属性 中删除或将它们添加到模型的 $fillable
属性 中。不要同时使用 $guarded 和 $fillable,您必须使用其中之一。在此处阅读完整文档:
MassAssigntmentException
是由于您正在更新的字段不是 fillable
并且因此被保护免受分配,为此您需要在 Question
class.
public class Question
{
protected $fillable = [
'question',
'type_based_id',
];
}