Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joseangelcrn/c5f6bdd9a80c7b04123adfeb01c5c633 to your computer and use it in GitHub Desktop.
Save joseangelcrn/c5f6bdd9a80c7b04123adfeb01c5c633 to your computer and use it in GitHub Desktop.

under taggable model

<?php

use Illuminate\Database\Eloquent\Relations\MorphPivot;

class Taggable extends MorphPivot
{
    protected $table = 'taggables';

    /* -------------------------------------------------------------------------- */
    /*                                  RELATIONS                                 */
    /* -------------------------------------------------------------------------- */

    public function tag()
    {
        return $this->belongsTo(Tag::class);
    }

    public function related()
    {
        return $this->morphTo(__FUNCTION__, 'taggable_type', 'taggable_id');
    }
}

under tag model

<?php

class Tag extends Model
{
    protected $with = ['taggables.related'];
    
    /* -------------------------------------------------------------------------- */
    /*                                  RELATIONS                                 */
    /* -------------------------------------------------------------------------- */

    public function taggables()
    {
        return $this->hasMany(Taggable::class);
    }
    
    /* -------------------------------------------------------------------------- */
    /*                                  ACCESSORS                                 */
    /* -------------------------------------------------------------------------- */

    public function getRelatedModelsAttribute()
    {
        return $this->taggables->groupBy('taggable_type');
    }
}

under the related model

<?php

public function tags()
{
    return $this->morphToMany(Tag::class, 'taggable')
                ->using(Taggable::class);
}

now use it like

Tag::first()->related_models;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment