What you are doing is perfectly fine because it simply get the job done. I personally would do the same if that's something I need to achieve fast and if it's a small application where all it's doing is inside this controller.
That being said, here are few things you can consider if you still want to improve this:
- I guess
$results,$keyand$valuehave these names for the sake of the example. But if I am wrong and that's really how you named the variables, then it would be cooler to name these better. In Laravel we value such small things. - Many folks would use the
Collectioninstance you have (your$resultsvariable) and will get rid of theforeachin favour of collection method calledtransform. That would also get rid of the temporary variable$resultsas it would be redundant. More about the method in the docs - If that's a bigger application, a good thing would be to clean your controller from that logic. The more "Laravel-ish" way of doing this is to create a custom request instance and move the transformation logic there. Then your controller could end up looking similar to just
return $request->applyTransformers(Something::select('created_at', 'value')->get());
Edit: Oh, I don't know how I missed that Something is actually an Eloquent model. Then all you should do is to create an accessor called getCreatedAtAttribute() inside the Something class and move the transformation logic there. Then your controller could end up as simple as return Something::all(); (in case created_at and value are all the columns you have in the database, or if you don't mind selecting few columns you won't need) More about accessors in the docs