vits / laravel-save-relationships
Save Laravel model relationships.
0.1.0
2024-10-22 12:33 UTC
Requires
- php: ~8.2
- illuminate/database: ^10.0|^11.0
Requires (Dev)
- ext-pdo_sqlite: *
- mockery/mockery: ^1.6
- orchestra/testbench: ^9.2
- pestphp/pest: ^2.34
- pestphp/pest-plugin-watch: ^2.1
README
Saves one or more Laravel model HasMany
, MorphsMany
or BelongsToMany
relationships by assigning relationhip id values as model attributes. Saving ir done in model's saved
event. Relationship data must be validated before saving. If transactional integrity is needed, it must be implemented in calling code.
Installation
composer require vits/laravel-save-relationships
Usage
use Vits\LaravelSaveRelationships\SaveRelationships; class Author extends Model { use SaveRelationships; protected $saveRelationships = 'books'; public function books(): HasMany { return $this->hasMany(Book::class); } } ... $author->books = [1, 2, 3]; $author->save();
Multiple relationship names may be given as comma separated string or as array.
protected $saveRelationships = 'books,series'; // or protected $saveRelationships = ['books', 'series'];
Relationship may be saved by custom method. In this case all relationshop saving logic must be implemented in this method.
protected $saveRelationships = ['books' => 'saveBooks']; protected function saveBooks($books) { //... }