LaravelPackages.net
Acme Inc.
Toggle sidebar
haithemkdous/laravel-7-has-many-sync

Laravel has many sync

17
0
1.2.0
About haithemkdous/laravel-7-has-many-sync

haithemkdous/laravel-7-has-many-sync is a Laravel package for laravel has many sync. It currently has 0 GitHub stars and 17 downloads on Packagist (latest version 1.2.0). Install it with composer require haithemkdous/laravel-7-has-many-sync. Discover more Laravel packages by haithemkdous or browse all Laravel packages to compare alternatives.

Last updated

Laravel HasMany Sync

Allow sync method for Laravel Has Many Relationship.

Installation

You can install the package via composer:

composer require haithemkdous/laravel-7-has-many-sync

Register the ServiceProvider in config/app.php

'providers' => [
    // ...
    Alfa6661\EloquentHasManySync\ServiceProvider::class,
],

Usage

Setup HasMany Relation

class Customer extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function contacts()
    {
        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

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);

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');
    }
}

Star History Chart