'Difference between save, fill, create in laravel eloquent
So i am new to laravel, I don't know the difference between save, fill and create in laravel eloquent. can anybody describe it?
Solution 1:[1]
save() method is when you already assign a value to a model instance. for example
$user = new User;
$user->name = "anything";
$user->save();
dd($user); // {'id': 1, 'name': 'anything'}
save() can also for update a value
$user = User::first(); // { 'id': 1, 'name': "anything" }
$user->name = "change";
$user->save();
dd($user); // {id: 1, name: "change"}
create() is a static function, need array parameter to create a new record
$user = User::create(['name' => 'new user']);
dd($user); // {id: 2, name: 'new user'}
fill() is same like save() method but without create a new record. need to create a new instance before can use fill()
$user = new User;
$user->fill(['name' => 'last user']);
echo count(User::all()); // We count users on DB and result is 2
$user->save(); // This will save 'last user' to DB
echo count(User::all()); // result is 3
Solution 2:[2]
The are kinda the same, but not quite.
//Creating User with fill()
$user = new User();
$user->fill($validatedUserData);
$user->save();
//Creating User with create();
$user = User::create($validatedUserData);
As you can see, create can do all of 3 lines(with fill function) with just one line. That's essentially a quality of life feature.
Both of this shown above does the same thing.
With that being said, you'd probably want to use create() when making a new entry. But for updating an item, it's better to just do something like this:
public function update(User $user, Request $request){
$validatedUserData = $request->validate([
//Validation logic here
]);
$user->fill($validatedUserData);
$user->save();
}
Note: You need to mark fields as fillable to use those fields with create() or fill().
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 | Localhousee |
| Solution 2 |
