Call Laravel model by string

- 1 answer

Ad

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'
Ad

Answer

Ad

Yes, you can do this, but you need to use the fully qualified class name:

$model_name = 'App\Model\User';
$model_name::where('id', $id)->first();

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.

$model = $this->model_name;
$model::where('id', $id)->first();
Ad
source: stackoverflow.com
Ad