Reputation: 2199
I understand Laravel is checking the object reference id
to check if the object existed, so the save()
method will run the edit
method to edit it. and if it's a new object, it will run the create()
method.
but I can't find the codes behind it, in the Eloquent package.
I want the exact address of the file that includes these codes
from the blow codes I infer the above conclusion:
I wrote this code in Laravel:
$setting = new Setting;
$setting->name = 'name1';
$setting->save();
$setting->name = 'name2';
$setting->save();
after executing I see just name2
in the database and it seems, after saving name1
Laravel edit that and save name2
in the database.
and after I execute this code:
$setting = new Setting;
$setting->name = 'name1';
$setting->save();
$setting = new Setting;
$setting->name = 'name2';
$setting->save();
and I saw both the records saved correctly, so I have name1
and name2
.
Upvotes: 0
Views: 293
Reputation: 174
You can find the code for Eloquent's save()
method in vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
on line 833 in Laravel 8.12.
The behaviour that you're observing is a characteristic of the Active Record pattern, which Laravel is based on. Each time you use new
to create an Eloquent model, it's creating a object that will represent a row in your database. Within Eloquent's save()
method, it will check to see if a record already exists, and if it does it will update it (code below).
if ($this->exists) {
$saved = $this->isDirty() ?
$this->performUpdate($query) : true;
}
Your code is working as expected.
Upvotes: 1