Looks like that is not the new question. But I have not found out any real solutioin. Here is my code to expected it will work:
$update_pet=pets::where("pet_id",$pet['pet_id'])->get();
if($update_pet->count()>0){
$update_pet=$update_pet->first();
$update_pet->pet_breed_id=$pet_new['pet_breed_id'];
$update_pet->save();
}
I am sure that $pet['pet_id'] and $pet_new['pet_breed_id'] has value. And I am sure table pet_breeds in database has primary key as pet_id. The system can connect the database as I can get the pet_id and new pet_breed_id. And I am sure I have overwrite table name and primaryKey value in model.
class pets extends Model
{
protected $table="pets";
protected $primaryKey="pet_id";
}
And it does not updated even. Per now I am just directly using DB::update() to run the update query to solve the problem. But I still want to know why it is happening? Or is it something wrong in the coding? Or the save function cannot used in update situation now?
Why make things complicated?
pets::find($pet['pet_id'])->update(['pet_breed_id' => $pet_new['pet_breed_id']]);
Also either include this line:
protected $guarded = [];
or this one:
protected $fillable = ['pet_breed_id'];
in your pets model class.
One last thing, you should start all your classes name with capital. And model names should not be a plural. So...
class Pet extends Model
Try to get an object instead of collection:
$pet = pets::find($pet['pet_id']);
if (!is_null($pet)) {
$update_pet->pet_breed_id = $pet_new['pet_breed_id'];
$update_pet->save();
}
Also, make sure you're getting the right object by putting dd($pet); right after the first line of the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With