如何解决数组错误时仅调用成员函数()的问题



在更新某些字段之前,我想使用laravels FormRequest进行验证。如果我只使用,这很好

User::find($application->userid)->fill($request->only('first_name'...

但是该请求还包含子数组($request->programmeData(。

array:2 [▼
"programme_id" => 5
"programme_title" => "some programme title"
]

如果我尝试以相同的方式访问它,我会得到"仅调用数组上的成员函数((":

Course::find($application->userid)->fill($request->programmeData->only('programme_id...

我试过一些东西,但不确定最好的方法是什么?

更新
我现在使用foreach循环来保存数组中的两个项目。下面的示例保存了两个userid的第二个值。为什么不保存第一个userid的第一个值?

foreach ($request->programmeData['userProgrammes'] as $key=>$userProgrammes) {
Course::where('application_id', $application->id)->get()[$key]->fill(Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id']))->save();
}

但没有任何更新。关于这个有什么想法吗?

您可以使用Array::only()助手进行以下操作:

foreach ($request->programmeData['userProgrammes'] as $key=>$userProgrammes) {
Course::where('application_id', $application->id)->first()->fill([
$key => Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id'])
])->save();
// or
$course = Course::where('application_id', $application->id)->first()
$course->$key = Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id']);
$course->save();
}
//Arr::only($request->programmeData, ['programme_id', ...]);