3

I have A Model In Laravel stored in variable as String.

$model = "App\Models\City";

What I want is

$model::find(1) to fetch the City with ID of 1

But It's not working as it is expected. However, when I do

City::find(1)

Not using the $model variable. I can fetch my expected result.

Anyone?

John Roca
  • 1,164
  • 1
  • 13
  • 27

3 Answers3

5

You could resolve the class out of service container

$model = app("App\Models\City");
$model::find(1);
linktoahref
  • 7,186
  • 3
  • 28
  • 47
3

You can use this, you can refer How can I call a static method on a variable class? for more.

$city = call_user_func($class . '::find', 1);
LF00
  • 24,667
  • 25
  • 136
  • 263
3

You can use call_user_func

Try this:

$model = "App\Models\City";
$id =1
$city = call_user_func(array($model, 'find'), $id);
R.K.Saini
  • 2,668
  • 1
  • 17
  • 25