Modifying dates returned by query

Posted 10 months ago by mr-grayda

I'm teaching myself Laravel by porting an API I wrote in vanilla PHP. The API does nothing too fancy -- a scheduled task takes an assortment of text files, grabs the values and dates within and stores them in the database. Later, when requested, the data is just grabbed, almost verbatim from the database, and returned as JSON.

One feature of my original API was the ability to modify the UTC dates returned by passing a timezone as a query string (for example: http://api.example.com/v1/something?tz=Australia%2FMelbourne).

Right now I've replicated this feature by taking the results of the query in my controller, modifying them, then returning them. But I feel like there's a more Laravel-y way to do this. I've heard of people using PHP's Traits feature to do this, but I'm not sure how I'd use that.

Here's a sample controller that shows what I'm doing:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Validator;
use App\Something; // Model
use Carbon\Carbon;

class SomethingController extends Controller
{

  function get(Request $request) {
    $results = Something::select('created_at', 'value')->get();

    foreach($results as $key => $value) {
      $results[$key]['created_at'] = (new Carbon($results[$key]['created_at']))->setTimezone($request->query('tz'))->__toString();
    }

    return $results;
  }

Any suggestions?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.