0
0
LaravelHow-ToBeginner · 3 min read

How to Use Update in Eloquent: Laravel Guide

In Laravel Eloquent, use the update method on a model instance or query builder to modify existing records. You pass an array of column-value pairs to update, which updates the matching database rows.
📐

Syntax

The update method accepts an associative array where keys are column names and values are the new data to save. It can be used on a model instance or a query builder.

  • Model instance: Updates a single record.
  • Query builder: Updates all records matching the query.
php
// Using update on a model instance
$user = User::find(1);
$user->update(['name' => 'New Name']);

// Using update on a query builder
User::where('active', false)->update(['active' => true]);
💻

Example

This example shows updating a user's name by finding the user first, then calling update. It also shows updating multiple users at once using a query.

php
<?php
use App\Models\User;

// Update single user
$user = User::find(1);
$user->update(['name' => 'Alice']);

// Update multiple users
User::where('subscribed', false)->update(['subscribed' => true]);
Output
User with ID 1 now has name 'Alice'. All users with subscribed = false now have subscribed = true.
⚠️

Common Pitfalls

Common mistakes include:

  • Calling update on a model without first retrieving it (causes error).
  • Not passing an array to update.
  • Expecting update to return the updated model (it returns a boolean).

Always retrieve the model before updating if you want to update a single record.

php
// Wrong: calling update on model class directly
// User::update(['name' => 'Bob']); // Error

// Right: retrieve then update
$user = User::find(2);
$user->update(['name' => 'Bob']);
📊

Quick Reference

UsageDescription
$model->update(['field' => 'value'])Update single model instance
Model::where(...)->update(['field' => 'value'])Update multiple records matching query
Returns booleanTrue if update succeeded, false otherwise
Requires arrayPass an associative array of columns and values

Key Takeaways

Use update with an array of column-value pairs to modify records.
Retrieve a model instance before calling update for single record updates.
The update method returns a boolean, not the updated model.
You can update multiple records at once using query builder with where and update.
Always pass an associative array to update to avoid errors.