Reputation: 1110
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.
Upvotes: 0
Views: 222
Reputation: 18187
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();
Upvotes: 1
Reputation: 7420
Add another slash to your class name:
$class = "\App\Models\$model";
instead of :
$class = "App\Models\$model";
Upvotes: 0