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,204
  • 1
  • 14
  • 27

3 Answers3

5

You could resolve the class out of service container

$model = app("App\Models\City");
$model::find(1);
linktoahref
  • 7,812
  • 3
  • 29
  • 51
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
  • 27,015
  • 29
  • 156
  • 295
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,678
  • 1
  • 18
  • 25