Search code examples
phplaravelmodels

Make model dynamically using user supplied model name in laravel


I am stuck with it and i couldn't find any appropriate solution for this. what i want to achieve is in my admin panel based upon check box value i want to change active status of specific control and update database value using ajax. I want to make a common ajax function in controller to avoid repeatedly writing same ajax function for other controls like menu manager content manager, documents manager etc.So i want to send Model name to the ajax controller so that same function can be used. Ajax call is working perfectly but couldn't make appropriate models. for example: $m = new App\Model.$request->model OR $m = 'App\Model\'.$request->model (adding last \ gives an error) or answer provided in Dynamically use model in laravel is not helping either. Is there any better ways if yes please suggest. I can do this below but it is hardcoded so i want to make model dynamic models

if($request->model ==='Menu')
        $model = new \App\Http\Models\Menu;
    else if($request->model === 'News')
        $this->model = new \App\Http\Models\News;
    else if($request->model === 'Document')
    $this->model = new \App\Http\Models\Document;

Thankyou !!!


Solution

  • You can just use:

    $modelName = '\\App\\Http\\Models\\'.$request->model;
    $this->model = new $modelName;
    

    However you should add validation to make sure only some allowed models would be used or at least do something like this:

    if (! in_array($request->model, ['Menu', 'News', 'Document']))
    {
       throw new \Exception('Invalid model');
    }
    $modelName = '\\App\\Http\\Models\\'.$request->model;
    $this->model = new $modelName;
    

    This is because you don't want to expose probably all the models data for security reasons.