Rami
Rami

Reputation: 171

Eloquent Update function is not updating all records

i want to update all user records depending on the user id , the user id is repeated more than one time and i want the update function to update all these occurrences here is my try :

App\Models\HistoryCostEstimation::where(['user_id'=>$user_ID])->update(['currency'=>$currenc]);

but this code updates only one occurrence , is there any other way to do the required purpose ?

this is the table structure enter image description here

and this is a sample of the data in the table

enter image description here

Upvotes: 0

Views: 1342

Answers (2)

samtoya
samtoya

Reputation: 79

Solution:

$user_id = 1;
$records = App\HistoryCostEstimation::where('user_id', $user_id)
                                        ->update(['cost_name' => 'New value']);

Note: The eloquent where clause takes string parameters not an array, also make sure your $fillable fields are set. That should do the trick.

Upvotes: 3

Rami
Rami

Reputation: 171

well i found where the mistake is , the problem was that i'm taking the query inputs from a web service.

imagine the scenario that the mobile app sends me id and based on this id i did the query above in the question and i didn't but in mind that all the results are taken during the run time not before it the code was like

$HistoryCostEstimationID = $request->input('historyCostEstimationID');

  $type = $request->input('type');
  $newValue = $request->input('newValue');  
  $currenc = $request->input('currency');

  $user_ID = App\Models\HistoryCostEstimation::select('user_id')->where('id',$HistoryCostEstimationID)->get();
  App\Models\HistoryCostEstimation::where('user_id', $user_ID)->update(['currency'=>$currenc]);
  App\Models\HistoryCostEstimation::where(['id' => $HistoryCostEstimationID])->update([ $type => $newValue , 'currency' => $currenc]);

but it has to be something like

$HistoryCostEstimationID = $request->input('historyCostEstimationID');

  $type = $request->input('type');
  $uID = $request->input('u_id');
  $newValue = $request->input('newValue');  
  $currenc = $request->input('currency');

  App\Models\HistoryCostEstimation::where('user_id', $uID)->update(['currency'=>$currenc]);
  App\Models\HistoryCostEstimation::where(['id' => $HistoryCostEstimationID])->update([ $type => $newValue , 'currency' => $currenc]);

i mean i had to take the u_id before executing the query because if it is not , it will always give null

Upvotes: 0

Related Questions