morphTo(__FUNCTION__, 'item_type', 'item_id'); } public function relatedItem(): MorphTo { return $this->morphTo(__FUNCTION__, 'related_item_type', 'related_item_id'); } public function creator() { return $this->belongsTo(User::class, 'created_by'); } /** * All edges touching a given model, either as owner or as target (symmetric view). */ public static function forItem(Model $model) { return static::where(function ($query) use ($model) { $query->where('item_type', $model->getMorphClass())->where('item_id', $model->getKey()); })->orWhere(function ($query) use ($model) { $query->where('related_item_type', $model->getMorphClass())->where('related_item_id', $model->getKey()); }); } /** * The model on the "other side" of this edge, relative to the given model. */ public function otherItem(Model $relativeTo): ?Model { $isOwner = $this->item_type === $relativeTo->getMorphClass() && (string) $this->item_id === (string) $relativeTo->getKey(); return $isOwner ? $this->relatedItem : $this->item; } }