Format array of dates

4

I have a Laravel application with the following code:

private function todosRegistros($id, $colunas = ['data', 'nivel'])
{
    return Leitura::select($colunas)->where('estacao_id', $id);
}

public function _24horas($estacao_id)
{
    return $this->todosRegistros($estacao_id)
        ->where('data', '>', Carbon::now('America/Sao_Paulo')
            ->subDay())->get();
}

When you run the _24hour method, I get a array with the level values and the corresponding registration date.

It turns out that the returned date comes in the American format (YYYY-mm-dd) and would like it to come in the Brazilian format (dd/mm/YYYY) . Using Carbon::parse I can change date to date in array but I would like an alternative where I modify all at once. Does anyone have any idea how to do this?

Thank you.

    
asked by anonymous 15.10.2018 / 21:44

1 answer

1

In the simplest way, I'd make a appends and a method for that field to fetch the date and move to d/m/Y H:i:s (or d/m/Y ) format, example / strong>:

Model

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Leitura extends Model
{

    protected $fillable = ['name']; 

    protected $appends = ['created_at_br'];

    public function getCreatedAtBrAttribute()
    {
        $value = date_create($this->attributes['created_at']);
        if ($value)
        {
            return $value->format('d/m/Y H:i:s');           
        }
        return null;
    }
}

in this example in array of appends the name created_at_br was inserted and an accessor with the name getCreatedAtBrAttribute was also created, get meant to retrieve the value and name of the appends with initials in capsules and finally Attribute at the end, which is the default for accessor methods.

After the search, look at the example:

>>> App\Models\Leitura::find(1)->toArray()
=> [
     "id" => 1,
     "name" => "Stackoverflow",
     "created_at" => "2018-10-17 20:25:32",
     "updated_at" => "2018-10-17 20:25:32",
     "created_at_br" => "17/10/2018 20:48:18",
   ]

In this example the data obtained does not interfere with those that are related to the database, they do not disturb the formats that are used for example in CRUD .

Reference Eloquent: Serialization - Appending Values To JSON

In your case it could be:

protected $appends = ['data_br'];

public function getDataBrAttribute()
{
    $value = date_create($this->attribue['data']);
    if ($value)
    {
        return $value->format('d/m/Y H:i:s');           
    }
    return null;
}

If your bank is MySQL another solution is SQL :

Leitura::select(\DB::raw("date_format('data','%d/%m/%Y'),'nivel'"))
       ->where('estacao_id', $id)
       ->get();
    
18.10.2018 / 01:53