Laravel Update: How to Update Database Data

In the Laravel framework, updating database data typically requires using Eloquent ORM (Object-Relational Mapping). Here is a simple example to demonstrate how to update database data in Laravel.

Assuming there is a model called User, we want to modify a field named name.

use App\Models\User;

$user = User::find(1); //通过主键查找到需要修改的记录

$user->name = 'New Name';
$user->save();

In this example, we start by using the User::find(1) method to locate the user record with id 1, then we update the name field to ‘New Name’, and finally we call the $user->save() method to save the modified data.

In addition to directly modifying field values, you can also use the update method to simultaneously modify multiple field values.

User::where('id', 1)->update(['name' => 'New Name', 'email' => 'newemail@example.com']);

The above is the basic method of modifying database data. Using Laravel’s Eloquent ORM allows us to operate the database in an object-oriented way, making the code clearer and easier to maintain.

bannerAds