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.
You can install the package via composer with following command:
composer require f-liva/laravel-hasmany-sync
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'], ...]);
I am open for suggestions and contributions. Just create an issue or a pull request.
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.
The composer fix
command formats the code with php-cs-fixer.
The composer lint
command checks the code with phpcs.
This package is licensed under the MIT License (MIT). Please see license file for more information.