aw-studio/laravel-dynamic-relations

v0.1.0 2021-10-20 08:44 UTC

This package is auto-updated.

Last update: 2024-11-20 16:16:03 UTC


README

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.