Laravel Eloquent Find doesn't work when modeling strings

I have a model in Laravel stored in a variable as a String.

$model = "App\Models\City";

      

I want to

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

      

But it doesn't work as expected. However, when I do

City::find(1)

      

Don't use the $ model variable. I can get the expected result.

Anyone?

+3


source to share


3 answers


You can decide the class from the service container



$model = app("App\Models\City");
$model::find(1);

      

+4


source


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



$city = call_user_func($class . '::find', 1);

      

+3


source


You can use call_user_func

Try the following:

$model = "App\Models\City";
$id =1
$city = call_user_func(array($model, 'find'), $id);

      

+3


source







All Articles