Skip to content

RelationHelper

The RelationHelper is a helper class that is used to work with model relations. It allows easy query building based on model relations.

Class

php
<?php

namespace App\Helpers;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class RelationHelper
{
    public static function fromRelation(Model $model, string|int $modelId, string $relation): Builder
    {
        $modelInstance = $model->findOrFail($modelId);

        return $modelInstance->$relation()->getQuery();
    }

    public static function notFromRelation(Model $model, string|int $modelId, string $relation): Builder
    {
        $modelInstance = $model->findOrFail($modelId);
        $modelInstance->$relation()->get()->pluck('id')->toArray();

        return $modelInstance
            ->$relation()
            ->getRelated()
            ->whereNotIn(
                'id',
                $modelInstance
                    ->$relation()
                    ->get()
                    ->pluck('id')
                    ->toArray()
            );
    }
}

Methods

fromRelation

  • Type: function (Model $model, string|int $modelId, string $relation): Builder
  • Description: Fetches models related to the given model via the provided relation.

notFromRelation

  • Type: function (Model $model, string|int $modelId, string $relation): Builder
  • Description: Fetches models not related to the given model via the provided relation.