Updating data
Updating Documents in Firestore Eloquent Library
Updating documents in Firestore is a common operation, and the Firestore Eloquent Library in Laravel provides convenient methods to perform updates. Let's explore how to update documents using the library's features.
Partial Update with update()
The update()
method allows you to update a single document in a Firestore collection. You can use this method to update fields of a document that match certain conditions.
Basic Update
Let's update the age
field of the document with the id
1234
in the users
collection.
// Update a user with the specified ID
$userId = '1234';
$user = User::find($userId);
$updatedUser = $user->update([
'age' => 30
]);
Update Multiple Fields
You can also update multiple fields of a document. Let's update the status
and age
fields of the document with the id
1234
in the users
collection.
// Update a user with the specified ID
// Update a user with the specified ID
$user = User::where(['user_id', '=', $userId])->first();
$updatedUser = $user->update([
'age' => 30,
'status' => 'inactive'
]);
// Update a user with the specified ID
$user = User::where(['user_id', '=', $userId])->firstOrFail();
$updatedUser = $user->update([
'age' => 30,
'status' => 'inactive'
]);