75

In my Laravel application I have an Faq model. An Faq model can contain many Product models, so the Faq class contains the following function:

class Faq extends Eloquent{ 
    public function products(){
        return $this->belongsToMany('Product');
    }
}

In a controller, I would like to be able to retrieve the class name that defines the relationship. For example, if I have an Faq object, like this:

$faq = new Faq();

How can I determine the class name of the relationship, which in this case would be Product. Currently I am able to do it like this:

$className = get_class($faq->products()->get()->first());

However, I'm wondering if there is a way to accomplish this same thing without having to actually run a query.

flyingL123
  • 7,686
  • 11
  • 66
  • 135

1 Answers1

180

Yes, there is a way to get related model without query:

$className = get_class($faq->products()->getRelated());

It will work for all relations.

This will return full name with namespace. In case you want just base name use:

// laravel helper:
$baseClass = class_basename($className);

// generic solution
$reflection = new ReflectionClass($className);
$reflection->getShortName();
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157
  • getRelated is a great find! Previously I was using $className = get_class($faq->products()->getQuery()->getModel()); – malhal Aug 06 '15 at 23:06