PHPackages                             iksaku/laravel-mass-update - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. iksaku/laravel-mass-update

ActiveLibrary[Database &amp; ORM](/categories/database)

iksaku/laravel-mass-update
==========================

Update multiple Laravel Model records, each with different values, using a single query!

1.0.8(1y ago)1351.3M↑14.3%12[1 issues](https://github.com/iksaku/laravel-mass-update/issues)[1 PRs](https://github.com/iksaku/laravel-mass-update/pulls)3MITPHPPHP ^8.2CI failing

Since Jun 28Pushed 1mo ago3 watchersCompare

[ Source](https://github.com/iksaku/laravel-mass-update)[ Packagist](https://packagist.org/packages/iksaku/laravel-mass-update)[ Docs](https://github.com/iksaku/laravel-mass-update)[ RSS](/packages/iksaku-laravel-mass-update/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (13)Used By (3)

Laravel Mass Update
===================

[](#laravel-mass-update)

[![Latest Version on Packagist](https://camo.githubusercontent.com/26db66e6da9f8fa38ac5f8a3675a32185cace96ff6aa6dd94f66a8369af994ac/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696b73616b752f6c61726176656c2d6d6173732d7570646174652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iksaku/laravel-mass-update)[![GitHub Tests Action Status](https://camo.githubusercontent.com/351d9cf7c2ab35d6eee6dc77cd1b46a48fcea23df847132bc24f9d0962b4405b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f696b73616b752f6c61726176656c2d6d6173732d7570646174652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473)](https://github.com/iksaku/laravel-mass-update/actions/workflows/run-tests.yml?query=branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/476ba742aa1721fbe64684733bad617309b3a067418d64c9b5a770b02a52185e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f696b73616b752f6c61726176656c2d6d6173732d7570646174652f7068702d63732d66697865722e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65)](https://github.com/iksaku/laravel-mass-update/actions/workflows/php-cs-fixer.yml?query=branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/23d288cce5fbba05334e360eece5597cd180b995c9ee702a88899054cac395e6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f696b73616b752f6c61726176656c2d6d6173732d7570646174652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iksaku/laravel-mass-update)

Update multiple Laravel Model records, each with its own set of values, sending a single query to your database!

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require iksaku/laravel-mass-update
```

Usage
-----

[](#usage)

In your model class, add the `Iksaku\Laravel\MassUpdate\MassUpdatable` trait:

```
use Illuminate\Database\Eloquent\Model;
use Iksaku\Laravel\MassUpdate\MassUpdatable;

class User extends Model
{
    use MassUpdatable;

    // ...
}
```

And that's all! Your model is now ready to update multiple records with varying values in a single query!

Let's take a look at some possible use cases for this new query:

### Simple use case: Update the values of multiple records

[](#simple-use-case-update-the-values-of-multiple-records)

Imagine that you have the following `users` table:

idnameusername1Jorge Gonzalesiksaku2Gladys Martinesgm\_mtzBut, we want to update both records since those users have told us that their legal last name was misspelled:

- `González` is written with an accent on the letter `a`, and only uses `z`, never an `s`.
- `Martínez` is written with an accent on the letter `i`, and last letter should be a `z`, not an `s`

Well, we can mass update those specific records:

```
User::massUpdate(
    values: [
        ['id' => 1, 'name' => 'Jorge González'],
        ['id' => 2, 'name' => 'Gladys Martínez'],
    ]
);
```

Now, both records will be updated with their corresponding values in a single query, resulting in:

idnameusername1Jorge Gonzáleziksaku2Gladys Martínezgm\_mtzBy default, the `massUpdate` query will grab your model's primary key name and apply it as part of the query to not affect other records.

If you want to use another column as an index to separate value types, you could pass it as a second argument to the function call:

```
User::massUpdate(
    values: [
        ['username' => 'iksaku', 'name' => 'Jorge González'],
        ['username' => 'gm_mtz', 'name' => 'Gladys Martínez'],
    ],
    uniqueBy: 'username'
);
```

### Simple use case #2: Updating multiple Eloquent Models

[](#simple-use-case-2-updating-multiple-eloquent-models)

If you need to update the values in some Model classes and want to automatically mass update those changes, then this is for you!

The existing `masUpdate` query is capable of identifying the *dirty* attributes of `Eloquent` model classes and compile them properly. You don't need to manually convert the models into an array, you just pass the list of models you want to update, and it takes care of the rest.

> Tip: If you pass a full list of `Eloquent` models, only those with *dirty* values will be updated, so you don't actually need to filter the unchanged ones manually.

Let's recreate the previous example, but using `Eloquent` models...

```
// Say we already pulled our user models previously... Something like this:
$jorge = User::where('name', 'Jorge Gonzales')->first();
$gladys = User::where('name', 'Gladys Martines')->first();

// And let's say we already made changes to those models... Like this:
$jorge->name = 'Jorge González';
$gladys->name = 'Gladys Martínez';

// And now, let's update both models in a single query:
User::massUpdate(
    values: [$jorge, $gladys]
);
```

Pretty cool, right?

> Note: It is only possible to mass update instances of the same `Eloquent` model, it is not possible to mix the *Query Builder* with different `Eloquent` model classes.

### Complicated use case: Using multiple indexes to differentiate records

[](#complicated-use-case-using-multiple-indexes-to-differentiate-records)

Let's say that we just created `expenses` table to track how much we spend across time, and we manually filled the following values:

idyearquartertotal\_expenses..........2019Q3216.70..2019Q4216.70..2020Q1`416.70`..2020Q2211.12..2020Q3113.17..2020Q4422.89..2021Q1`431.35`> Above information is not real, I don't track my expenses quarterly.

Oops... We made a little mistake... Expenses from Q1 of 2020 and 2021 are switched, and in order to fix it we could only pass the `quarter` column as an index, but if we only pass down the `quarter` column as an index, we'll modify **ALL** `Q1` records. So, for this, we should also pass down the `year` column as an index:

```
Expense::massUpdate(
    values: [
        ['year' => 2020, 'quarter' => 'Q1', 'total_expenses' => 431.35],
        ['year' => 2021, 'quarter' => 'Q1', 'total_expenses' => 416.70],
    ],
    uniqueBy: ['year', 'quarter']
);
```

> Tip: If you ever need to specify more than one or two indexes, just include all of them in the `values` and `uniqueBy` parameters.

The result in the table will be properly updated:

idyearquartertotal\_expenses..........2020Q1`431.35`..........2021Q1`416.70`> **NOTE**: It is important that you always include the `uniqueBy` columns in your `values` array, exceptions will be thrown otherwise.

> **NOTE #2**: It is not possible to update the values of the `uniqueBy` columns. Every column specified in this parameter will be filtered from the ones that are going to be updated.
>
> This prevents unexpected side effects from happening while updating `values`in `array` shape and passed as `Eloquent` models.

### Advanced use case: Chaining with other query statements

[](#advanced-use-case-chaining-with-other-query-statements)

Let's try to keep things simple and imagine a system that tracks *To-Do* items for multiple users:

iduser\_idcontentorder11Pick up my daughter221Buy a new ThinkPad131Drink water3Like every *To-Do* system, we let our users `order` their *To-Do* items to see the most important ones at the top of the list, and to do this, we may be using a [simple sorting package](https://github.com/asantibanez/laravel-blade-sortable)that allows the user to drag items up and down the list.

Once the user moves one item in the list, in the backend we may receive an array with a specific key-value shape: `['position' => 'id']`. With this, we're going to update the records' `position` based on the given `id`.

We can simply call our `massUpdate` query function and everything will be done... Well, sort of...

In this specific scenario, we're dealing with **multiple lists for multiple users**, that means that we may not be always able to control which `id` columns are sent to the server, maybe some malicious actor wants to hijack our *To-Do* list and lower the priority for buying ThinkPads. This is a pretty serious security concern.

There are many ways to solve this kind of issues, and a simple one is to *chain query statements* to our `massUpdate` function.

In this case, we're going to add a `where()` statement to only update those items that belong to the currently logged in user. And it's as simple as in any other Laravel query builder:

```
TodoItem::query()
    ->where('user_id', auth()->id())
    ->massUpdate(
        values: collect($request->input('item_order'))
            ->mapWithKeys(
                fn ($id, int $position) => ['id' => $id, 'order' => $position]
            )
    );
```

> Tip: Did you know you can pass Collections, LazyCollections, Eloquent Collections and basically any `Arrayable` instance as `values` to the `massUpdate` query function?

This can be used as an extra layer to ensure data integrity when dealing with User-provided input that affects multiple records in the database.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Jorge González](https://github.com/iksaku)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

59

—

FairBetter than 99% of packages

Maintenance70

Regular maintenance activity

Popularity56

Moderate usage in the ecosystem

Community23

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 89.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~149 days

Recently: every ~189 days

Total

10

Last Release

443d ago

Major Versions

1.0.7 → 2.x-dev2024-09-21

PHP version history (3 changes)1.0.0PHP ^8.0

2.x-devPHP ^8.1

1.0.8PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/16e6f847fc85f78ca2828648d5c05bbf59a45eece0ef9979f5a16b7c2c930110?d=identicon)[iksaku](/maintainers/iksaku)

---

Top Contributors

[![iksaku](https://avatars.githubusercontent.com/u/4632429?v=4)](https://github.com/iksaku "iksaku (51 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (3 commits)")[![adamczykpiotr](https://avatars.githubusercontent.com/u/20736260?v=4)](https://github.com/adamczykpiotr "adamczykpiotr (1 commits)")[![cwilby](https://avatars.githubusercontent.com/u/13686317?v=4)](https://github.com/cwilby "cwilby (1 commits)")[![Ing-LuisGuerrero](https://avatars.githubusercontent.com/u/48639261?v=4)](https://github.com/Ing-LuisGuerrero "Ing-LuisGuerrero (1 commits)")

---

Tags

eloquentlaravelphpsqllaraveliksakularavel-mass-update

###  Code Quality

TestsPest

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/iksaku-laravel-mass-update/health.svg)

```
[![Health](https://phpackages.com/badges/iksaku-laravel-mass-update/health.svg)](https://phpackages.com/packages/iksaku-laravel-mass-update)
```

###  Alternatives

[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8703.0M17](/packages/yajra-laravel-oci8)[cybercog/laravel-love

Make Laravel Eloquent models reactable with any type of emotions in a minutes!

1.2k302.7k1](/packages/cybercog-laravel-love)[cviebrock/eloquent-taggable

Easy ability to tag your Eloquent models in Laravel.

567694.8k3](/packages/cviebrock-eloquent-taggable)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
