Use model names dynamically if you have its name as a string

376 0 0 0

Last Updated : 2024-05-02 02:05:27

Sometimes, you will need to use/call models/classes dynamically if you only have its fully qualified name as a string. So for example if you have a record and you got its class|model name using get_class($record), and now you need to access this model using the name you have right now. then you can use the following snippet to do so.

$theBaseClassName = get_class($record);
$model = app("{$theBaseClassName}");
$model = app(get_class($record)); //Same as previous
//Now you can access different attributes from this class as follows:
$model->indexName; // IndexName property.
$model->getTable(); //Model Table

//Another way is as follows:
$baseModelName = 'Bill';
$modelName = "\\App\Models\\".$baseModelName; \\Note the use of double back slashes
$theModel = new $modelName();

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .