Derek M.
Derek M.

Reputation: 89

Laravel query to output json data as select list. How to amend existing code to concatenate two values

I've got a pre-existing function in my controller that will run a simple query and return the model_name and id then return the result as json.

public function getModel($id) 
{
    $models = DB::table('model')->where('man_id',$id)->pluck('model_name','id');
    return json_encode($models);
}

New requirement is that I include an additional column named model_num with the query. Plan is to concatenate the model_name and model_num columns.

Tried the following, but it doesn't return any values and I get a 404 response for the json:

public function getModel($id) 
{
    $models = DB::table("model")->select("id","CONCAT(model_name, '-', model_num) as model")->where("man_id",$id)->pluck('model','id');
    return json_encode($models);
}

Am I missing something obvious?

Upvotes: 0

Views: 475

Answers (2)

nikistag
nikistag

Reputation: 694

public function getModel($id) { $models = DB::table('model')->where('man_id',$id)->first() ; $models->model = $models->model_name. '-'. $models->model_num; return json_encode($models->pluck('model', 'id'); }

Upvotes: 0

apokryfos
apokryfos

Reputation: 40690

You are using SQL functions within a select these will probably not work. You can use selectRaw instead:

public function getModel($id) 
{
    $models = DB::table("model")
        ->selectRaw("id, CONCAT(model_name, '-', model_num) as model")
        ->where("man_id",$id)
        ->pluck('model','id');
    return response()->json($models); // response()->json() is preferable
}

alternatively you can do the concatenating in the PHP side:

public function getModel($id) 
{
    $models = DB::table("model")
        ->select("id", "model_name" "model_num")
        ->where("man_id",$id)
        ->get()
        ->mapWithKeys(function ($model) {
            return [ $model->id => $model->model_name.'-'.$model->model_num ];
        })
    return response()->json($models);
}

Upvotes: 1

Related Questions