ChatGPT解决这个技术问题 Extra ChatGPT

Laravel get class name of related model

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.


J
Jarek Tkaczyk

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();

getRelated is a great find! Previously I was using $className = get_class($faq->products()->getQuery()->getModel());