0

I am trying to access dynamically models so that I can get the count for each of them depending on which string I pass to the function. This is what my function in the controller looks like:

public function numberOf(Request $request){
    $modelName = $request['option'];
    $model = new $modelName;
    $data = $model->count();

    return json_encode($data);
  }

But when I pass a string, like in this case 'Article' I get an error:

Fatal error: Class 'Article' not found

Even though I am calling it in the controller:

use App\Article;
2
  • Did you set up the name spaces? Commented May 18, 2016 at 11:03
  • Yes, and it is working fine in the other function in the same controller when I am using Article model like this: $numberOfArticles = Article::count(); Commented May 18, 2016 at 11:05

1 Answer 1

3

I had to add App to model name, so that my function looks like this now and everything works fine now:

$modelName = 'App\\'.$request['option'];
$model = new $modelName;
$data = $model->count();

return json_encode($data);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.