我正在进行一个Laravel项目,并试图实现一种动态补丁方法,仅当请求中提供特定字段时,才能更新模型中的特定字段。我已经编写了以下代码,但我想知道是否有更高效或更干净的方法来实现这一点:
public function updateShipModule(ShipModulesRequest $request, $id)
{
$data = $request->validated();
// Find the record by ID
$module = ShipModules::findOrFail($id);
// Update only the is_workable field
if ($request->has('is_workable')) {
$module->is_workable = $data['is_workable'];
}
if ($request->has('module_name')) {
$module->module_name = $data['module_name'];
}
$module->save();
return response()->json(['data' => $module]);
}
此外,我在请求类的验证规则中包含了以下代码,以处理补丁请求:
public function rules(): array
{
$rules = [
'is_workable' => 'required|boolean',
'module_name' => 'sometimes|required|String|min:3|max:25|unique:ship_modules',
];
if ($this->isMethod('patch')) {
// Add the 'sometimes' rule for module_name
$rules['is_workable'] = 'sometimes|' . $rules['is_workable'];
$rules['module_name'] = 'sometimes|' . $rules['module_name'];
}
return $rules;
}
我想知道这种处理请求验证中“module_name”字段的“有时”规则的方法是否正确,是否符合最佳实践。
有没有更好的方法可以在不显式检查每个字段的情况下,根据提供的数据处理动态更新?我想保持代码的整洁,避免重复,因为字段的数量可能会增加。
我想知道这种处理请求验证中“module_name”字段的“有时”规则的方法是否正确,是否符合最佳实践。