Search code examples
phplaravellaravel-5.1

Call Laravel model by string


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'

Solution

  • 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();