Table of contents

laravel 9 - update existing model

In this post, I will show you an example of how to implement using Laravel 9 on Update an Existing Model. Laravel model update is one of the most functionality we should learn when creating an application using Laravel. In this post, we have different methods and examples of how to do it. Just pick one that is suitable for your needs.

 

Example #1:

 

$employee = Employee::find(1);

$employee->name = "Juan Dela Cruz";

$employee->save();

 

Example #2:

We can also update the model using an array with multiple values which don't need to use the save() method.

 

$employee = Employee::find(1);

$employee->update(['name' => 'Juan Dela Cruz', 'address' => 'My address']);

 

Example #3:

We can also update records with a conditional method using where function directly.

 

Employee::where('salary', '>', '10000')
	->update([
		'address' => 'Juan Dela Cruz', 
		'address' => 'My address'
	]);

 

Example #4:

If you don't need to change the updated_at column when updating the record you may use the touch option as false so that the model will exclude it.

 

$employee = Employee::find(1);

$employee->update([
	'name' => 'Juan Dela Cruz', 
	'address' => 'My address'
], ['touch' => false]);