PHPackages                             korridor/laravel-has-many-sync - 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. korridor/laravel-has-many-sync

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

korridor/laravel-has-many-sync
==============================

Laravel has many sync

3.1.0(1y ago)3578.1k↓14.9%3[3 PRs](https://github.com/korridor/laravel-has-many-sync/pulls)MITPHPPHP &gt;=8.1CI passing

Since Aug 10Pushed 5mo agoCompare

[ Source](https://github.com/korridor/laravel-has-many-sync)[ Packagist](https://packagist.org/packages/korridor/laravel-has-many-sync)[ Docs](https://github.com/korridor/laravel-has-many-sync)[ RSS](/packages/korridor-laravel-has-many-sync/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (7)Versions (12)Used By (0)

Laravel HasMany Sync
====================

[](#laravel-hasmany-sync)

[![Latest Version on Packagist](https://camo.githubusercontent.com/9c54f803c5d4f3e142de1ee0728e191c0371694066393f9edcda04d5b5e9f8ce/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b6f727269646f722f6c61726176656c2d6861732d6d616e792d73796e633f7374796c653d666c61742d737175617265)](https://packagist.org/packages/korridor/laravel-has-many-sync)[![License](https://camo.githubusercontent.com/7453c63e945d051474955a73224fd46621c68f86b2f424aa47f32cfd56fe37bb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6b6f727269646f722f6c61726176656c2d6861732d6d616e792d73796e633f7374796c653d666c61742d737175617265)](license.md)[![GitHub Workflow Lint](https://camo.githubusercontent.com/49d872c97a8818c532f08a6767e1956fd1fac354032275f29f189033ab524d6f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6b6f727269646f722f6c61726176656c2d6861732d6d616e792d73796e632f6c696e742e796d6c3f6c6162656c3d6c696e74267374796c653d666c61742d737175617265)](https://github.com/korridor/laravel-has-many-sync/actions/workflows/lint.yml)[![GitHub Workflow Tests](https://camo.githubusercontent.com/fa7e6bf53fd191e40332b0237895d87ac6462ed6ab9753cfec2fa7feee57a019/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6b6f727269646f722f6c61726176656c2d6861732d6d616e792d73796e632f756e697474657374732e796d6c3f6c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/korridor/laravel-has-many-sync/actions/workflows/unittests.yml)[![Codecov](https://camo.githubusercontent.com/779fac463f62147602a75b597a8b4e58c0d87939e822d6e5aae750ab6362c83a/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6b6f727269646f722f6c61726176656c2d6861732d6d616e792d73796e633f7374796c653d666c61742d737175617265)](https://codecov.io/gh/korridor/laravel-has-many-sync)

Allow sync method for Laravel Has Many Relationship.

Note

Check out **solidtime - The modern Open Source Time-Tracker** at [solidtime.io](https://www.solidtime.io)

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

[](#installation)

You can install the package via composer with following command:

```
composer require korridor/laravel-has-many-sync
```

If you want to use this package with older Laravel/PHP version please install the 1.\* version.

```
composer require korridor/laravel-has-many-merged "^1"
```

**Warning: The 1.\* versions use a different namespace!**

### Requirements

[](#requirements)

This package is tested for the following Laravel and PHP versions:

- 10.\* (PHP 8.1, 8.2, 8.3)
- 11.\* (PHP 8.2, 8.3, 8.4)
- 12.\* (PHP 8.2, 8.3, 8.4)

Usage
-----

[](#usage)

### Setup HasMany Relation

[](#setup-hasmany-relation)

```
class Customer extends Model
{
    /**
     * @return HasMany
     */
    public function contacts(): HasMany
    {
        return $this->hasMany(CustomerContact::class);
    }
}
```

You can access the sync method like this:

```
$customer->contacts()->sync([
    [
        'id' => 1,
        'name' => 'Alfa',
        'phone_number' => '123',
    ],
    [
        'id' => null,
        'name' => 'Adhitya',
        'phone_number' => '234,
    ]
]);
```

The sync method accepts an array of data to place on the intermediate table. Any data that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the data in the given array will exist in the intermediate table.

#### Syncing without deleting

[](#syncing-without-deleting)

If you do not want to delete existing data, you may pass false value to the second parameter in the sync method.

```
$customer->contacts()->sync([
    [
        'id' => 1,
        'name' => 'Alfa',
        'phone_number' => '123',
    ],
    [
        'id' => null,
        'name' => 'Adhitya',
        'phone_number' => '234,
    ]
], false);
```

#### Behaviour for IDs that are not part of the hasMany relation

[](#behaviour-for-ids-that-are-not-part-of-the-hasmany-relation)

If an ID in the related data does not exist or is not in the scope of the `hasMany` relation, the `sync` function will throw a `ModelNotFoundException`. It is possible to modify this behavior with the `$throwOnIdNotInScope` attribute. Per default, this is set to `true`. If set to false, the `sync` function will ignore the Ids instead of throwing an exception.

```
$customer->contacts()->sync([
    [
        'id' => 7, // ID that belongs to a different customer than `$customer`
        'name' => 'Peter',
        'phone_number' => '321',
    ],
    [
        'id' => 1000, // ID that does not exist
        'name' => 'Alfa',
        'phone_number' => '123',
    ],
    [
        'id' => null,
        'name' => 'Adhitya',
        'phone_number' => '234,
    ]
], throwOnIdNotInScope: false);
```

#### Example usage in the controller.

[](#example-usage-in-the-controller)

```
class CustomersController extends Controller
{
    /**
     * Update the specified resource in storage.
     *
     * @param  CustomerRequest  $request
     * @param  Customer $customer
     * @return \Illuminate\Http\Response
     */
    public function update(CustomerRequest $request, Customer $customer)
    {
        DB::transaction(function () use ($customer, $request) {
            $customer->update($request->all());
            $customer->contacts()->sync($request->get('contacts', []));
        });

        return redirect()->route('customers.index');
    }
}
```

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

[](#contributing)

I am open for suggestions and contributions. Just create an issue or a pull request.

### Local docker environment

[](#local-docker-environment)

The `docker` folder contains a local docker environment for development. The docker workspace has composer and xdebug installed.

```
docker-compose run workspace bash
```

### Testing

[](#testing)

The `composer test` command runs all tests with [phpunit](https://phpunit.de/). The `composer test-coverage` command runs all tests with phpunit and creates a coverage report into the `coverage` folder.

### Codeformatting/Linting

[](#codeformattinglinting)

The `composer fix` command formats the code with [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer). The `composer lint` command checks the code with [phpcs](https://github.com/squizlabs/PHP_CodeSniffer).

Credits
-------

[](#credits)

This package is a fork of [alfa6661/laravel-hasmany-sync](https://github.com/alfa6661/laravel-hasmany-sync).

License
-------

[](#license)

This package is licensed under the MIT License (MIT). Please see [license file](license.md) for more information.

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance58

Moderate activity, may be stable

Popularity42

Moderate usage in the ecosystem

Community12

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 66.7% 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 ~342 days

Recently: every ~369 days

Total

8

Last Release

441d ago

Major Versions

1.2.2 → 2.0.02023-02-19

2.0.0 → 3.0.02024-03-01

PHP version history (2 changes)1.2.0PHP ^7.1|^8

2.0.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/728181ca75a1f175821f8adf7526047da19253c88ec012b236031f4fab1c5cf0?d=identicon)[korridor](/maintainers/korridor)

---

Top Contributors

[![korridor](https://avatars.githubusercontent.com/u/26689068?v=4)](https://github.com/korridor "korridor (12 commits)")[![alfa6661](https://avatars.githubusercontent.com/u/3650559?v=4)](https://github.com/alfa6661 "alfa6661 (4 commits)")[![bianchi](https://avatars.githubusercontent.com/u/1824997?v=4)](https://github.com/bianchi "bianchi (1 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

laravellaravel-eloquentlaravel-packagephplaraveleloquentrelationssynchas-many

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/korridor-laravel-has-many-sync/health.svg)

```
[![Health](https://phpackages.com/badges/korridor-laravel-has-many-sync/health.svg)](https://phpackages.com/packages/korridor-laravel-has-many-sync)
```

###  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)[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)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[korridor/laravel-has-many-merged

Custom relationship for Eloquent that merges/combines multiple one-to-may (hasMany) relationships

90122.5k1](/packages/korridor-laravel-has-many-merged)

PHPackages © 2026

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