Relational

Relational

Simplest relationships (Parents/Children) for model.

Moamen Eltouny (Raggi)
PHP Version : >= 7.2 Laravel Version : >= 6.0 License Support
Source Packagist Version Packagist Downloads

Example

$category = Category::find(1);
$post = Post::find(1);
    
// Create/Update Child
$category->attach($post)

// Retrieve Category's Posts
$children = $category->children;

foreach($children as $record){
    dump($record->child->record);
}
Install

Install the latest version using Composer

composer require pharaonic/laravel-relational

Then publish the migration & migrate.

php artisan vendor:publish --tag=laravel-relational
php artisan migrate
Usage

How to use

Include HasRelationships into the model.

// An Example : (Post Model)
// Using hasRelationships in Post Model
...
use Pharaonic\Laravel\Relational\HasRelationships;

class Post extends Model
{
    use HasRelationships;
...
Parents

Attach To Parent

Attach one/more objects to a parent.

// Object
$post->attachTo($category);

// List of Objects
$post->attachTo($category1, $category2);
// OR
$post->attachTo([$category1, $category2]);

Retrieve Object Parents

Getting single/Multiple parents of a single object.

// Single
$parent = $post->parent;

// Multi
$parents = $post->parents;
Children

Attach Child

Attach one/more objects to a parent.

// Object
$category->attach($post);

// List of Objects
$category->attach($post1, $post2);
// OR
$category->attach([$post1, $post2]);

Detach Child

Detach single/Multiple object from a parent.

// Object
$category->detach($post);

// List of Objects
$category->detach($post1, $post2);
// OR
$category->detach([$post1, $post2]);

Retrieve Object Children

Getting single/multiple children object of a parent object.

// Single
$child = $category->child;

// Multi
$children = $category->children;