Call Laravel model by string

2019-01-25 05:33发布

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'

4条回答
来,给爷笑一个
2楼-- · 2019-01-25 06:20

Yes you can do it with more flexible way. Create a common function.

function getWhere($yourModel, $select, $is_model_full_path=null, $condition_arr=null)
{
    if(!$is_model_full_path){ // if your model exist in App directory
        $yourModel ="App\\$yourModel";
    }
    if(!$condition_arr){
        return $yourModel::all($select)->toArray();
    }
    return $App_models_yourModel::all($select)->where($condition_arr)->toArray();
}

Now you can call this method in different ways.

getWhere('User', ['id', 'name']); // with default path of model
getWhere('App\Models\User', ['id', 'name'], true); // with custom path of model
getWhere('User', ['id', 'name'], false, ['id', 1]); // with condition array

By the way I like to use such functions.

查看更多
3楼-- · 2019-01-25 06:22

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();
查看更多
做自己的国王
4楼-- · 2019-01-25 06:22

if you use it in many of the places use this function

function convertVariableToModelName($modelName='',$nameSpace='App')
        {
            if (empty($nameSpace) || is_null($nameSpace) || $nameSpace === "") 
            {                
               $modelNameWithNameSpace = "App".'\\'.$modelName;
                return app($modelNameWithNameSpace);    
            }

            if (is_array($nameSpace)) 
            {
                $nameSpace = implode('\\', $nameSpace);
                $modelNameWithNameSpace = $nameSpace.'\\'.$modelName;
                return app($modelNameWithNameSpace);    
            }elseif (!is_array($nameSpace)) 
            {
                $modelNameWithNameSpace = $nameSpace.'\\'.$modelName;
                return app($modelNameWithNameSpace);    
            }
        }

Example if you want to get all the user

Scenario 1:

 $userModel= convertVariableToModelName('User');
  $result = $userModel::all();

Scenario 2:

if your model in in custom namespace may be App\Models

$userModel= convertVariableToModelName('User',['App','Models']);
$result = $userModel::all();

Hope it helps

查看更多
时光不老,我们不散
5楼-- · 2019-01-25 06:27

Try this:

$model_name = 'User';
$model = app("App\Model\{$model_name}");
$model->where('id', $id)->first();
查看更多
登录 后发表回答