'Laravel Model save() & update() Not Saving
Laravel 5.7
Hello I have been looking through stack overflow and have tried many possible answers and have come to no conclusions.
I am updating a simple integer value in a patron table through simple checks and it is not updating the database. I have tried using save()
and update()
methods on the model.
There are no errors or exceptions that show up and the save()
and update()
methods return true
.
code:
Controller Class Using the model and updating data:
$patron_coupon = PatronCoupons::where('owner',$patron_id)->where('coupon_id',$active_coupon['coupon_id'])->first();
if($patron_coupon->current_uses > $active_coupon['max_uses'])
$patron_coupon->current_uses = $active_coupon['max_uses'];
// if i echo $patron_coupon->current_uses here, it will show that this value has changed ( good )
$patron_coupon->current_uses = $active_coupon['max_uses'] - $patron_coupon->times_used;
if($patron_coupon->current_uses < 0)
$patron_coupon->current_uses = 0;
// this doesnt work
$patron_coupon->save();
// this doesnt work either
$patron_coupon->update($patron_coupon->toArray());
// if i echo current_uses here, the value goes back to what it was before being set.
Model Class:
class PatronCoupons extends Model
{
protected $table = 'patron_coupons';
protected $primaryKey = 'owner';
public $timestamps = false;
protected $fillable = ['times_used','current_uses','settings_version'];
}
Migration File:
Schema::create('patron_coupons', function (Blueprint $table) {
$table->string('owner'); // patron id that 'owns' this coupon
$table->unsignedInteger('coupon_id'); // id of this coupon
$table->unsignedInteger('current_uses')->default(0); // the amount of uses this patron has for this coupon
$table->unsignedInteger('settings_version')->nullable();// last settings version fetch
$table->unsignedInteger('times_used')->default(0); // amount of times this coupon has been used
});
Please help, I've been banging my head on my desk for hours !!!!!
Solution 1:[1]
You can try any of the following:
Try using static
update
function insteadPatronCoupons::update([ // updates here ]);
Remove your
vendor
folder andcomposer.lock
file. Then runcomposer install
to refresh your vendor file
Solution 2:[2]
get record
$patronCoupons = PatronCoupons::find($id);
$patronCoupons->update([
'times_used' => 'value',
'current_uses' => 'value',
'settings_version' => 'value'
]);
if your post data with the same input name then directly use
$post = $request->all();
$patronCoupons = PatronCoupons::find($id);
$patronCoupons->update($post);
Solution 3:[3]
Make sure that you put this code in the form because of which the error occurs
'enctype' => 'multipart/form-data'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jonathan K |
Solution 2 | Natvarsinh Parmar - bapu |
Solution 3 | Tyler2P |