Home » Php » php – Laravel get class name of related model

php – Laravel get class name of related model

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

How to&Answers:

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

Answer:

I think you cannot do that. I don’t know what you need it for, but you could simply add extra method where you put all your relations class name and where you return one you want:

public function getRelationsClassName($relation) {
    $relations = [
        'products' => 'Product',
        'users' => 'User',
    ]  
    return isset($relations[$relation]) ? $relations[$relation] : null;
}