How do I update existing records in the database using Eloquent?
Jun 12, 2025 am 11:01 AMTo update records in the database, first retrieve the target record, then modify the properties and save. 1. Use find(), where() and other methods to obtain model instances; 2. Modify model attribute values; 3. Call the save() method to save changes; 4. For conditional batch updates, you can use the update() method of the query constructor; 5. Pay attention to the triggering of events and timestamps, and ensure that the fields are in $fillable or are properly verified. The whole process is simple and flexible, but input and logical dependencies need to be handled with caution.
Updating existing records in a database using Eloquent is straightforward once you understand the flow. The key is to retrieve the record, modify its attributes, and then save the changes.
Find the Record You Want to Update
Before updating anything, you need to fetch the specific record from the database. This is usually done using methods like find()
, where()
, or other query constraints.
For example:
$user = User::find(1);
This gets the user with an ID of 1. If you're not sure if the record exists, consider using findOrFail()
which will throw an exception if nothing is found.
Sometimes you might want to use a condition instead, like:
$user = User::where('email', 'test@example.com')->first();
Make sure that your query actually returns a model instance before trying to update it.
Modify and Save the Model
Once you have the model instance, you can change any of its properties just like you would with a regular PHP object.
For example:
$user->name = 'New Name'; $user->email = 'newemail@example.com'; $user->save();
Calling save()
on the model persists the changes back to the database. It's important to remember that this only updates the specific fields you've changed — Eloquent doesn't overwrite unrelated columns unless told to do so (eg, by using touch()
or mass assignment).
- Make sure the fields you're updating are listed in the
$fillable
array in your model. - Timestamps (
updated_at
) are automatically updated when you callsave()
.
If you're updating multiple rows at once based on a condition without needing to process each model individually, you can also use:
User::where('active', false)->update(['name' => 'Inactive User']);
Just keep in mind that this method doesn't fire model events or update timestamps unless you handle that manually.
Handle Mass Updates Carefully
When you want to update multiple fields at once using an array, Eloquent allows this too:
$user->update([ 'name' => 'Jane Doe', 'email' => 'jane@example.com' ]);
This is essentially a shortcut for setting multiple attributes and calling save()
.
However:
- Be cautious with mass updates if validation or access control is involved.
- Always validate input data before passing it into
update()
. - Use policies or form requests if you're accepting user input directly.
Also, note that update()
can be used directly on a query builder instance:
User::where('role', 'guest')->update(['role' => 'member']);
Again, this won't trigger model events, so consider that when designing logic that depends on them.
That's basically how you update records using Eloquent. Get the record, make your changes, and save. Whether you're updating one record or many, Eloquent gives you flexible tools to get the job done — just pay attention to when events and timestamps are triggered.
The above is the detailed content of How do I update existing records in the database using Eloquent?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article brings you relevant knowledge about Laravel. It mainly introduces to you the implementation of optimistic locking in the Laravel Eloquent model. There are code examples. Friends who are interested can take a look below. I hope it will be helpful to you.

Laravel development: How to use LaravelEloquent to implement polymorphic associations? Polymorphic association is an important feature of Laravel Eloquent, which allows one model to establish relationships with multiple different models. In practical applications, processing different types of data is relatively simple and efficient, especially in database design. In this article, we will discuss how to implement polymorphic associations using Laravel Eloquent. 1. What is a polymorphic association? Polymorphism

Converting an array into an object using Eloquent in Laravel requires the following steps: Create an Eloquent model. Use Eloquent's select method to get the result and convert it to an array. Use ArrayObject to convert an array into an object. Gets an object property to access an array's values.

Laravel is a popular PHP framework that includes the powerful ORM (Object Relational Mapping) library-LaravelEloquent. This library is very powerful and can help us easily implement model association, making it easier to manage and query data. But many developers don't know how to use Laravel Eloquent to implement model association. In this article, I will introduce how to implement model association using Laravel Eloquent. 1. Laravel

Laravel is a popular PHP web framework that is popular due to its simplicity and ease of use. The Laravel framework is known for its excellent implementation of EloquentORM, an Object-RelationalMini mapping that supports the use of PHP to define database models and provides easy database interaction based on these models. This article will detail how to build a model using Laravel Eloquent to interact with the database quickly and reliably.

Laravel development: How to build a database model using LaravelEloquent? Laravel is a popular PHP framework that provides a powerful and easy-to-use database operation tool - Laravel Eloquent. In the past, using PHP to perform database operations inevitably required writing a large number of lengthy SQL statements and cumbersome codes. However, using Laravel Eloquent can easily build database models and achieve rapid development and maintenance. This article

As developers' needs for data interaction continue to grow, ORM has become an indispensable part of modern development. It can hide database operations in the background and provide a simplified API for CRUD operations. Among these ORM libraries, Eloquent has attracted the attention of many developers because it has been widely used in the Laravel framework. In PHP 8.0, Eloquent comes as a standalone extension library and can now be used in your projects. In this article we will explore Eloq

To create new records in the database using Eloquent, there are four main methods: 1. Use the create method to quickly create records by passing in the attribute array, such as User::create(['name'=>'JohnDoe','email'=>'john@example.com']); 2. Use the save method to manually instantiate the model and assign values ??to save one by one, which is suitable for scenarios where conditional assignment or extra logic is required; 3. Use firstOrCreate to find or create records based on search conditions to avoid duplicate data; 4. Use updateOrCreate to find records and update, if not, create them, which is suitable for processing imported data, etc., which may be repetitive.
