0

I am trying to load models dynamically in my controller based on route type. But when I run program I get a message saying "class not found". Here is my code and a link of stackoverflow which I used to fix my issue.

Code:

    $model = $this->getModelName($request->matchType);
    $class = "App\Models\$model";
    if($model && class_exists($class))
    {
        $data = $class::where('type_id',$type)->firstOrFail();
    }
    else
    {
        $data = MyModel::find($type);
    }

    return $this->showOne($data);

Link:

Load in models dynamically in Laravel 5.1

This is a good link but not working for me and why simple $model::all() not working.

aishazafar
  • 1,024
  • 3
  • 15
  • 35

2 Answers2

1

You need to use double backslashes:

$class = "App\\Models\\$model";

Try using the app helper to resolve the model:

$data = app($class)->where('type_id',$type)->firstOrFail();
Brian Lee
  • 17,904
  • 3
  • 41
  • 52
  • My mistake I was running wrong program for testing. This solution helped me. But I am interested to know the second part too why $class:all(); does not work where class=MyModel. MyModel::all() should work as I have add use MyModel too above in the beginning of file. – aishazafar Jul 29 '18 at 12:43
  • Even though you've imported the class, `$model` is just a string and PHP has no way of making the connection to the import. You should be able to do `app($model)::all()` however. – Brian Lee Jul 29 '18 at 12:47
0

Add another slash to your class name:

 $class = "\App\Models\$model";

instead of :

 $class = "App\Models\$model";
Leo
  • 7,274
  • 5
  • 26
  • 48
  • give more feed back not only its not working do a `$class = new \App\Models\ModelName; and a dd($class); ` – Leo Jul 29 '18 at 12:35