PHP, Laravel - Concatenation with String to Model

Viewed 911

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.

Symfony\Component\Debug\Exception\FatalThrowableError: Class 'Car' not found in file

How can I concatenate? Is it possible?

5 Answers
use App\Car; //place this at the top of your page. Make sure the model exists

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

Yes, you can concatenate a model depending upon the condition. Below, I have added a workable code to implement.

Import both model.

//use App\Car;
//use App\Train;

$isCar = true; // boolean condition to check whether it is a car or train
$classVariable = null;

if ($variable) {
    $classVariable = new Car();
}else{
    $classVariable = new Train();
}

$result = $classVariable->where('model', $value)->get();

//this will provide you a car model query
dd($result);

Better Approach

A better approach will be to use a Vehicle model and Vehicle Type. Add a vehicle_type_id in the vehicles table.

So whenever you need to retrieve car types, you can use

//Suppose vehicle_type_id for car is 1
$carVehicle = Vehicle::where('vehicle_type_id', 1)->get();
//Suppose vehicle_type_id for train is 2
$trainVehicle = Vehicle::where('vehicle_type_id', 2)->get();

It's Possible

use App\Car;
use App\Train;

/* Here You can now set Model name dynamically*/

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

I think one approach can as below:

$vehicle = Car::class; //this will dynamically add full namespace of Car class. 
$result = $vehicle::where('model', $value)->count() > 0;
Related