Home > OS >  Laravel - save model to $existing variable to check is field has been updated?
Laravel - save model to $existing variable to check is field has been updated?

Time:03-26

I'm trying to store a model instance to a variable to be able to store the existing values like so:

    $meal_booking = MealBooking::where('date', $date)
        ->first();

    $existing_meal_booking = $meal_booking;

 
    $meal_booking->date = $date;
    $meal_booking->save();


    dump($meal_booking);
    dump($existing_meal_booking);

However, when I dump out the $existing_meal_booking var, it shows the updates, although this should only be updated for the $meal_booking var. I'm unsure why updating and saving the $meal_booking is also updating the $existing_meal_booking?

Any help on how I can resolve this would be great, I need to be able to compare the model later in my logic. Thanks.

CodePudding user response:

I believe this is the fundamentals of programming.

$meal_booking is an object, which is of reference type. So when you assign it with another variable.

$existing_meal_booking = $meal_booking;

They both refer to the same object.

You you want a separate non-existing copy of the $meal_booking object, pls use the replicate method:

$existing_meal_booking = $meal_booking->replicate();

If you want to track what has been changed on a model object, I suggest using model events.

  • Related