priosshrsth
priosshrsth

Reputation: 1158

Is there any way to access laravel model dynamically through variable when model name is stored in variable?

Basically what I need to do is:

$x = 'Admin';
$model = new \ReflectionClass($x);
$model->getFieldList();

Where I have Admin model inside app folder. Obviously, this doesn't work. Does anyone have any idea? Can it be done?

Upvotes: 1

Views: 1884

Answers (4)

Abu Talha
Abu Talha

Reputation: 11

$model = 'App?Models?'.$model;
$model = str_replace('?','\\',$model);

return $model::products()->paginate();

Upvotes: 1

user10194690
user10194690

Reputation:

i use something like that in the controller constructor. here what i use:

1)first declare a variable in parent controller lets say: $route_model_name and $model_location.

  1. then add this to each child controller:

    function __construct() {
      parent::__construct();
      $this->setRouteModelName( 'model_route_name' );
      $this->setModelLocation( 'App\Models\ModelName' );
    }
    
  2. then you add a method in the parent controller to initialize the model class in order to be ready for making queries:

     /**
      * @return mixed
      */
     protected function getModelClass() {
         return app( $this->model_class );
     }
    
  3. then you can change the model location and route in each of the child controllers and still use the same method in the parent controller:

     public function edit( $id ) {
         return $this->getModelClass()::where( 'id', $id )->first();
     }
    

Upvotes: 0

Alihossein shahabi
Alihossein shahabi

Reputation: 4352

you can do this, but you need to use the fully qualified class name.for example My models are in the Model directory :

$model = 'App\Model\User';
$user=$model::where('id', $id)->first();

Upvotes: 2

Jerodev
Jerodev

Reputation: 33186

Firstly you need to add the namespace to your model. By default this is App\. So your string would have to be "\App\Admin". Now you can simply create a class instance using this string.

$x = '\\App\\Admin';
$model = new $x();

Upvotes: 6

Related Questions