1 year ago

Modifying dates returned by query

Posted 1 year 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:

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:


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.