TomBaine
TomBaine

Reputation: 773

Is there an efficient way of adding user_id using updateOrCreate?

I'm trying to add/update responses from a multi-field form using updateOrCreate.

I'm avoiding having to write out the second argument in full for each field in the form by using $request->all. However, this approach so far is precluding me from adding the value for user_id that is needed for the record to be complete. That value (`$userId') is obtained in the controller as shown:

  $userId = Auth::user()->id;

  $cropid = $request->id;
  Crop::updateOrCreate(['id'=>$cropid],$request->all());  

Is there a way of retaining the $request->all approach AND adding the user_id value?

Thanks, Tom.

Upvotes: 0

Views: 70

Answers (1)

Chin Leung
Chin Leung

Reputation: 14921

You can use array_merge to generate an array with both data:

$data = array_merge($request->all(), ['user_id' => $userId]);

Then you can use the generated $data in your updateOrCreate method:

Crop::updateOrCreate(['id' => $cropId], $data);

Upvotes: 5

Related Questions