Reputation: 1234
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?
Upvotes: 3
Views: 1891
Reputation: 7972
You could resolve the class out of service container
$model = app("App\Models\City");
$model::find(1);
Upvotes: 5
Reputation: 2708
You can use call_user_func
Try this:
$model = "App\Models\City";
$id =1
$city = call_user_func(array($model, 'find'), $id);
Upvotes: 3
Reputation: 28529
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);
Upvotes: 3