如果isDirty()方法更改了我的代码,那么它仅保存一个field(efirst)
的数据,并且可以正常工作。如果我有十个字段而不写每个字段名称,如何获得相同的结果?
控制器:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
$teacher->efirst = $request->efirst;
if ($teacher->isDirty()) {
$new_data = $teacher->efirst;
$old_data = $teacher->getOriginal('efirst');
if ($teacher->save()) {
$teacher->update($request->except('qual_id', 'id', 'profile_pic'));
DB::table('teacher_logs')->insert(
[
'user_id' => $user->id,
'teacher_id' => $teacher->id,
'old_value' => $old_data,
'new_value' => $new_data,
]);
}
}
}
答案 0 :(得分:-1)
如果不想多次写$teacher->field = $request->value;
,则可以使用循环:
foreach($request->except("_token") AS $field => $value){
$teacher->{$field} = $value;
}
if($teacher->isDirty()){
$new_data = [];
$old_data = [];
foreach($request->except("_token") AS $field => $value){
$new_data[$field] = $value;
$old_data[$field] = $teacher->getOriginal($field);
}
}
注意:您需要将$new_data
和$old_data
转换为数组,以便可以正确引用每个字段和值,并对插入teacher_logs
表进行一些附加逻辑处理,但这应该可以给您一个想法。