f-liva/laravel-hasmany-sync

Sync Laravel HasMany relationships with ease

v1.2.0 2024-06-04 12:39 UTC

This package is auto-updated.

Last update: 2024-11-04 13:34:13 UTC


README

Latest Version on Packagist License Codecov TravisCI StyleCI

With this package you will be able to synchronize your HasMany relationships just as you normally would for BelongsToMany relationships. The usage is the same, follow the official Laravel documentation.

Thanks to korridor/laravel-has-many-sync for the original idea. This package reconstructs the mechanism using the original Laravel approach and operation.

Installation

You can install the package via composer with following command:

composer require f-liva/laravel-hasmany-sync

Usage

Configure your HasMany relationship as you normally would

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

Synchronize the relationship as you normally would in a BelongsToMany relationship

$customer->contacts()->sync([1, 2, 3]);

// Or with attributes...

$customer->contacts()->sync([1 => ['name' => 'Foo'], 2 => ['name' => 'Bar'], 3]);

The sync method accepts the same parameters described in Eloquent Relationships - Syncing Relations

You can also synchronize the relationship without knowing the identifiers of the related records. In this case, specify in the call the syncRelatedKey: false parameter.

$customer->contacts()->sync([1, 2, 3], syncRelatedKey: false);

// Or with attributes...

$customer->contacts()->sync([['name' => 'Foo'], ['name' => 'Bar'], ...]);

Contributing

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

Testing

The composer test command runs all tests with phpunit. The composer test-coverage command runs all tests with phpunit and creates a coverage report into the coverage folder.

Codeformatting/Linting

The composer fix command formats the code with php-cs-fixer. The composer lint command checks the code with phpcs.

License

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