laravel fill or update

Solutions on MaxInterview for laravel fill or update by the best coders in the world

showing results for - "laravel fill or update"
Cadby
25 Oct 2020
1<?php
2$user = User::find(1);
3// This will update immediately
4$user->update(['first_name' => 'Braj', 'last_name' => 'Mohan']);
5
6//But what if you do not want to update immediately. Suppose you also want to make user active before the actual update. Then fill method comes handy.
7$user = User::find(1);
8// This will not update underlying data store immediately
9$user->fill(['first_name' => 'Braj', 'last_name' => 'Mohan']);
10// At this point user object is still only in memory with updated values but actual update query is not performed.
11// so we can have more logic here 
12$user->is_active = true;
13// Then finally we can save it.
14$user->save(); // This will also make user active
15
16//Update method is dumb and makes the query to database even if no values are changed. But save method is intelligent and calculates if you really changed anything and do not perform query if nothing has changed for example.
17
18$user = User::find(1);
19//suppose user object has following values after fetching
20// first_name = 'Braj';
21// second_name = 'Mohan';
22// is_active = true;
23// Then if you set the values like following without any change
24$user->is_active = true; // it is already true so no change
25$user->save(); // this won't perform any database query hence is efficient