0

I am using one function in controller for inserting in several different tables with different Models. I mean that in controller model is variable.

This code bellow works perfectly but i don't like syntax, i am pretty sure there must be some other ways than str_replace for calling model with \App\ in front of it's name.

Calling only by Model name without \App\ causes laravel error Class not found. I have written use \App\ModelName in controller's file but it still does't works.

public function storeCommon(Request $request){
   $model = '"\App\"'. $request->model;
   $model =  str_replace ( "\"", "", $model ) ;

   ........
   ........       

   $row['text'] = $request->text;
   ........
   ........
   $common = $model::create($row);
}

1 Answer 1

1

I would rather define array of possible models and use it within the code. This way you will protect your code against call for unwanted models and off course your code will be much readable:

protected $possibleModels = [
    'Model1' => \App\Model1::class,
    'Model2' => \App\Model2::class,
    ...
    ];

public function storeCommon(Request $request){
    if (!isset($this->possibleModels[$request->model])) {
        abort(404);
    }
    $model = $this->possibleModels[$request->model];
    $row['text'] = $request->text;
    ...
    $common = $model::create($row);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, was thinking about it getting model by variable from array because of this syntax problems, than i thought that there was too much code for removing bad syntax. Now i realized that it would be more protective too, nice idea mate thanks for it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.