Looking to hire Laravel developers? Try LaraJobs

laravel-dynamic-relations maintained by aw-studio

Last update
2021/10/20 10:44 (dev-main)
License
Links
Downloads
8

Comments
comments powered by Disqus

Laravel Dynamic Relations

A package for attaching/detaching dynamic relations to Elqouent Models.

See also: Laravel Dynamic Attributes

Setup

Install the package via composer:

composer require aw-studio/laravel-dynamic-relations

Publish the migrations:

php artisan vendor:publish --tag="dynamic-relations:migraitons"

Usage

Just add the HasDynamicRelations to a Model:

use Illuminate\Database\Eloquent\Model;
use AwStudio\DynamicRelations\HasDynamicRelations;

class Page extends Model
{
    use HasDynamicRelations;
}

And attach a relation:

$page = Page::create();

$page->attach('article', $article)

dd($page->article); // Is the attached article

The related Model can be detached using the detach method:

$page->detach('article', $article);

Attaching A Collection

You may wish to attach a collection of models for a "many" relation. This can be achieved by passing an instance of a collection as a second parameter to the attach method:

$page = Page::create();

$page->attach('article', collect([$article]));

dd($page->article); // A collection containing the attached article.