Is it possible to call a Laravel model by string?
This is what i'm trying to achieve but its failing:
$model_name = 'User';
$model_name::where('id', $id)->first();
I get the following exception:
exception 'ErrorException' with message 'Undefined variable: User'
Yes you can do it with more flexible way. Create a common function.
Now you can call this method in different ways.
By the way I like to use such functions.
Yes, you can do this, but you need to use the fully qualified class name:
If your model name is stored in something other than a plain variable (e.g. a object attribute), you will need to use an intermediate variable in order to get this to work.
if you use it in many of the places use this function
Example if you want to get all the user
Scenario 1:
Scenario 2:
if your model in in custom namespace may be
App\Models
Hope it helps
Try this: