Skip to content
Advertisement

PHP, Laravel – Concatenation with String to Model

Is is possible to concatenate a string to Model? The below doesn’t seem to work.

I have Car Model and Train Model. Vehicle will be either Car or Train.

$vehicle = 'Car';
$result = $vehicle::where('model', $value)->count() > 0;

The above code exists the following error.

SymfonyComponentDebugExceptionFatalThrowableError: Class ‘Car’ not found in file

How can I concatenate? Is it possible?

Advertisement

Answer

I think this is the closest to what you need, you don’t have to import anything since you have a dynamic value. (If you have 10 possible models you will have to import all of them)

So you should do something like this

$model = "Car";

$modelsPath = "\App\Models\";

$className = $modelsPath.$model;

// if you need an instance you do this
// $instance = new $className;

$result = $className::where('model', $value)->count() > 0;

dd($result);

What i usually do is create a config file that contains an array of all possibilities where they key is the type (Car,Bus,Train in ur example)

And then i get the value using the key which is the input (car) and the model path will be in the config! that way you can swap it later easy and attach more conditions related to that type of model etc.

I hope this makes sense

Regards

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement