Last Updated: February 25, 2016
·
4.7K
· wajatimur

Laravel Eloquent Dynamic Relationship

Create config file name relation.php with the following content.

<?php return array(
    'user' => array(
        'role' => function( $self ) {
            return $self->belongsTo('Role');
        }
    )
);

The user key in array representing current model and role is the relation model that we want to create. Then you need to put below piece of code in your base model, which is the user refer to this example.

public function __call($method, $parameters) {
    $class_name = class_basename( $this );

    #i: Convert array to dot notation
    $config = implode( '.', [ 'relation', $class_name, $method ] );

    #i: Relation method resolver
    if ( Config::has( $config ) ) {
        $function = Config::get( $config );
        return $function( $this );
    }

    #i: No relation found, return the call to parent (Eloquent) to handle it.
    return parent::__call($method, $parameters);
}

The __call method is a magic method in PHP, it will trigger when inaccessible method were called in the class. The code in this function will try to resolve the relation if any then return the necessary relation method.

Original ideas:
Kirk Bushell