f-liva / laravel-hasmany-sync
Sync Laravel HasMany relationships with ease
Requires
- php: ^7.1|^8
- illuminate/database: ^5.8|6.*|7.*|8.*|9.*
- illuminate/support: ^5.8|6.*|7.*|8.*|9.*
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16|^3
- orchestra/testbench: ^3.8|^4.0|^5.0|^6.0|^7
- phpunit/phpunit: ^7.0|^8.0|^9.0
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-11-04 13:34:13 UTC
README
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.