Search code examples
phplaravel-4eloquent

Get all relationships from Eloquent model


Having one Eloquent model, is it possible to get all its relationships and their type at runtime?

I've tried taking a look at ReflectionClass, but I couldn't find anything useful for this scenario.

For example, if we have the classic Post model, is there a way to extract relationships like this?

- belongsTo: User
- belongsToMany: Tag

Solution

  • To accomplish this, you will have you know the names of the methods within the model - and they can vary a lot ;)

    Thoughts:

    • if you got a pattern in the method, like relUser / relTag, you can filter them out

    • or loop over all public methods, see if a Relation object pops up (bad idea)

    • you can define a protected $relationMethods (note: Laravel already uses $relations) which holds an array with method.

    After calling Post->User() you will receive a BelongsTo or 1 of the other objects from the Relation family, so you can do you listing for the type of relation.

    [edit: after comments]

    If the models are equipped with a protected $with = array(...); then you are able to look into the loaded relations with $Model->getRelations() after a record is loaded. This is not possible when no record is loaded, since the relations aren't touched yet.

    getRelations() is in /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php

    But currently it doesn't show up in the api at laravel.com/api - this is because we got newer version