Search code examples
phplaraveleloquenteloquent-relationship

How do i resolve Call to a member function only() on array error


I want to use laravels FormRequest to validate before updating some fields. This works fine if i just use:

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

but the request also contains sub array ($request->programmeData).

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

if i try access that the same way i get 'Call to a member function only() on array':

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

I've tried a handful of things, but not sure best way to go with this?

Update
I'm now using a foreach loop to save two items in the array. the example below saves the second value for both user_ids. any reason this isn't saving the first value for the first user_id?

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();
}

but nothing updates. Any ideas on this one?


Solution

  • You can use Array::only() helper for this:

    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', ...]);