├── .gitignore ├── composer.json ├── LICENSE ├── README.md └── src └── ServiceProvider.php /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor 2 | composer.phar 3 | composer.lock 4 | .DS_Store 5 | .idea 6 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "alfa6661/laravel-has-many-sync", 3 | "description": "Laravel has many sync", 4 | "type": "library", 5 | "require": { 6 | "illuminate/support": "~5.4" 7 | }, 8 | "license": "MIT", 9 | "authors": [ 10 | { 11 | "name": "Alfa Adhitya", 12 | "email": "alfa2159@gmail.com" 13 | } 14 | ], 15 | "autoload": { 16 | "psr-4": { 17 | "Alfa6661\\EloquentHasManySync\\": "src" 18 | } 19 | }, 20 | "extra": { 21 | "laravel": { 22 | "providers": [ 23 | "Alfa6661\\EloquentHasManySync\\ServiceProvider" 24 | ] 25 | } 26 | }, 27 | "minimum-stability": "dev", 28 | "prefer-stable": true 29 | } 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Alfa Adhitya 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel HasMany Sync 2 | 3 | Allow sync method for Laravel Has Many Relationship. 4 | 5 | # Installation 6 | 7 | You can install the package via composer: 8 | 9 | ``` 10 | composer require alfa6661/laravel-has-many-sync 11 | ``` 12 | 13 | Register the ServiceProvider in `config/app.php` 14 | 15 | ```php 16 | 'providers' => [ 17 | // ... 18 | Alfa6661\EloquentHasManySync\ServiceProvider::class, 19 | ], 20 | ``` 21 | 22 | # Usage 23 | 24 | 25 | ## Setup HasMany Relation 26 | 27 | ```php 28 | class Customer extends Model 29 | { 30 | /** 31 | * @return \Illuminate\Database\Eloquent\Relations\HasMany 32 | */ 33 | public function contacts() 34 | { 35 | return $this->hasMany(CustomerContact::class); 36 | } 37 | } 38 | ``` 39 | 40 | You can access the sync method like this: 41 | 42 | ```php 43 | $customer->contacts()->sync([ 44 | [ 45 | 'id' => 1, 46 | 'name' => 'Alfa', 47 | 'phone_number' => '123', 48 | ], 49 | [ 50 | 'id' => null, 51 | 'name' => 'Adhitya', 52 | 'phone_number' => '234, 53 | ] 54 | ]); 55 | ``` 56 | 57 | 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: 58 | 59 | ### Syncing without deleting 60 | 61 | If you do not want to delete existing data, you may pass false value to the second parameter in the sync method. 62 | 63 | ```php 64 | $customer->contacts()->sync([ 65 | [ 66 | 'id' => 1, 67 | 'name' => 'Alfa', 68 | 'phone_number' => '123', 69 | ], 70 | [ 71 | 'id' => null, 72 | 'name' => 'Adhitya', 73 | 'phone_number' => '234, 74 | ] 75 | ], false); 76 | ``` 77 | 78 | 79 | ### Example usage in the controller. 80 | 81 | ```php 82 | class CustomersController extends Controller 83 | { 84 | /** 85 | * Update the specified resource in storage. 86 | * 87 | * @param CustomerRequest $request 88 | * @param Customer $customer 89 | * @return \Illuminate\Http\Response 90 | */ 91 | public function update(CustomerRequest $request, Customer $customer) 92 | { 93 | DB::transaction(function () use ($customer, $request) { 94 | $customer->update($request->all()); 95 | $customer->contacts()->sync($request->get('contacts', [])); 96 | }); 97 | 98 | return redirect()->route('customers.index'); 99 | } 100 | } 101 | ``` -------------------------------------------------------------------------------- /src/ServiceProvider.php: -------------------------------------------------------------------------------- 1 | [], 'deleted' => [], 'updated' => [], 20 | ]; 21 | 22 | /** @var HasMany $this */ 23 | 24 | // Get the primary key. 25 | $relatedKeyName = $this->getRelated()->getKeyName(); 26 | 27 | // Get the current key values. 28 | $current = $this->newQuery()->pluck($relatedKeyName)->all(); 29 | 30 | // Cast the given key to an integer if it is numeric. 31 | $castKey = function ($value) { 32 | if (is_null($value)) { 33 | return $value; 34 | } 35 | 36 | return is_numeric($value) ? (int) $value : (string) $value; 37 | }; 38 | 39 | // Cast the given keys to integers if they are numeric and string otherwise. 40 | $castKeys = function ($keys) use ($castKey) { 41 | return (array) array_map(function ($key) use ($castKey) { 42 | return $castKey($key); 43 | }, $keys); 44 | }; 45 | 46 | // Get any non-matching rows. 47 | $deletedKeys = array_diff($current, $castKeys( 48 | array_pluck($data, $relatedKeyName)) 49 | ); 50 | 51 | if ($deleting && count($deletedKeys) > 0) { 52 | $this->getRelated()->destroy($deletedKeys); 53 | $changes['deleted'] = $deletedKeys; 54 | } 55 | 56 | // Separate the submitted data into "update" and "new" 57 | // We determine "newRows" as those whose $relatedKeyName (usually 'id') is null. 58 | $newRows = array_where($data, function ($row) use ($relatedKeyName) { 59 | return array_get($row, $relatedKeyName) === null; 60 | }); 61 | 62 | // We determine "updateRows" as those whose $relatedKeyName (usually 'id') is set, not null. 63 | $updatedRows = array_where($data, function ($row) use ($relatedKeyName) { 64 | return array_get($row, $relatedKeyName) !== null; 65 | }); 66 | 67 | if (count($newRows) > 0) { 68 | $newRecords = $this->createMany($newRows); 69 | $changes['created'] = $castKeys( 70 | $newRecords->pluck($relatedKeyName)->toArray() 71 | ); 72 | } 73 | 74 | foreach ($updatedRows as $row) { 75 | $this->getRelated()->where($relatedKeyName, $castKey(array_get($row, $relatedKeyName))) 76 | ->update($row); 77 | } 78 | 79 | $changes['updated'] = $castKeys(array_pluck($updatedRows, $relatedKeyName)); 80 | 81 | return $changes; 82 | }); 83 | } 84 | } 85 | --------------------------------------------------------------------------------