New

Just launched: Vueblocks, a brand-new search engine for Vue packages! Explore Vueblocks →

jwohlfert23/laravel-sync-relations

Package to sync nested relations from request data
7,351
Install
composer require jwohlfert23/laravel-sync-relations
Latest Version:5.0.0
PHP:>=8.2
Laravel:10 · 11
Older releases:6 – 9
License:MIT
Last Updated:Mar 19, 2024
Links: GitHub  ·  Packagist
Maintainer: jwohlfert23

Laravel Sync Relations

Add this to your models:

use Jwohlfert23/LaravelSyncRelations/SyncableTrait;
...

class Post extends Model {
    use SyncableTrait;
}

And you can use it in your controllers like so:


public function update($id) {
    $post = Post::find($id);
    
    $post->saveAndSync(request()->input(), ['tags']);
}

Let's assume the following

  • Post model has a "hasMany" relationship with tags.
  • The request data looks like:
{
  "title": "My Post Title",
  "tags": [{
    "id": 1,
    "name": "My First Tag"
  }, {
     "name": "My Second Tag"
  }]
}

By running saveAndSync, it will iterate over the 2 tags provided in the request. Because the first one already exists, it will update that one and set the name to "My First Tag". The second one doesn't exist aleady so it will create it using the name "My Second Tag". After this controller processeed this request, you could run the following:

Post::find($id)->tags->pluck('name')

and get this:

["My First Tag", "My Second Tag"]

This package also works with "belongsToMany" and "belongsTo" relationship types. However, for those, it will not update/create the nested objects. It will only associate the existing models with the parent model (in other words, for these relationship, you must provide the primary key for each child).

Additionally, you could run saveAndSync(request()->input(), ['comments.author']) to do a nested sync.

Related Packages

poojajadav/hasmanysync

This trait can be sync data for hasmany relationship.

1,548 1
czim/laravel-nestedupdater

Eloquent model updater for nested relations data for Laravel.

54,240 19
omaximus/laravel-pivot-polymorph

Fully polymorphic pivot relations for laravel eloquent

26,322 2
stayallive/laravel-inverse-relations

HasMany, HasOne and MorphMany Eloquent relations with inverse hydration.

11,069 31

Version History

Version Released PHP Laravel License
5.0.0 >=8.2 ^10.0|^11.0 MIT
4.0.0 >=7.3 ^8.0|^9.0|^10.0 MIT
3.0.0 >=7.3 ^8.0|^9.0 MIT
2.3.0 >=5.5.9 >=6.0 MIT
2.2.1 >=5.5.9 >=6.0 MIT