Khuram
Khuram

Reputation: 1850

Laravel Update Method is not Working as Expected

I'm updating two fields for a records by using the following the code:

$companyPlan = CompanyPlan::whereCompanyId($companyId)->first();
$companyPlan->update(['plan_id' => $planId, 'next_plan_id' => $planId])

What it does is that it updates the plan_id field but not next_plan_id.

Both the plan_id and next_plan_id are in the $fillable array of the model.

It really is a strange behavior but I'm unable to know the reason why this is so.

protected $fillable = ['plan_id', 'next_plan_id'];
protected $hidden = [];

Upvotes: 2

Views: 8115

Answers (3)

Ari D
Ari D

Reputation: 9

This behavior is because your table doesnt have any primary keys, so eloquent cant update it properly( since it uses the primary key for updating a single model instance ).

You should select the row by its unique attributes and update it on the same query, like this:

CompanyPlan::where('company_id', $companyId)
    ->update(['plan_id' => $planId, 'next_plan_id' => $planId]);

By eliminating the first() method, you are doing your work in only one query:

"UPDATE company_plans WHERE company_id = $companyId". *

Upvotes: 0

Jonathan
Jonathan

Reputation: 11504

Try something like this instead:

CompanyPlan::where('company_id', $companyId)->first()
    ->update(['plan_id' => $planId, 'next_plan_id' => $planId]);

Upvotes: 3

sihombing_j
sihombing_j

Reputation: 41

Have you try this, like Kjell said in comments:

$companyPlan->plan_id = $planId;
$companyPlan->next_plan_id = $planId;
$companyPlan->save();

Upvotes: 1

Related Questions