Support the ongoing development of Laravel.io →
Database Eloquent Architecture
Last updated 1 year ago.
0

eval() was the best solution i could come up with to generating classes dynamic in runtime. not my ideal solution. Here is the code in case anyone would like to use it.

Supports using the relation methods as well. May not be the cleanest of code, But it does get the job done.

<?php

$model_confg = array(
    "Models" =>
        array(array('className'=> "Books", 'classTable'=>'books', "fillable" => "book_name"), array('className'=> "Authors", 'classTable'=>'authors', "fillable" => "")),
    "Relations" =>
    array("Authors" =>
    array("books" =>
        array("function" => function( $self ) {
            return $self->belongsToMany('Books');
        }
        ))));

function eloquent_dym_models($models)
{
    $eval = "";
    foreach ($models as $key => $value) {

        $recordType = $value['className'];
        $recordTable = $value['classTable'];
        $f = $value["fillable"];

        $eval .= "class $recordType extends Illuminate\Database\Eloquent\Model {

    protected \$table = '$recordTable';

    protected \$fillable = [$f];

    public function __call(\$method, \$parameters) {

    \$class_name = class_basename( \$this );

    if(array_key_exists(\$class_name, \$parameters[0])) {
    \$func = \$parameters[0][\$class_name][\$method]['function'];
    return \$func(\$this);
    }

    return parent::__call(\$method, \$parameters);

    }

    }";

    }

    eval($eval);
}

eloquent_dym_models($model_confg['Models']);

$authors = Authors::find(1);


$data['authors'] = $authors->toJson();
$data['books'] = $authors->books($model_confg['Relations'])->get()->toJson();

?>
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.