In the simplest way, I’d make a appends
and a method for this field to pick up the date and move to format d/m/Y H:i:s
(or d/m/Y
), example:
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;
}
}
that is, in this example in array
of appends
the name has been inserted created_at_br
and was also created an accessor with the name getCreatedAtBrAttribute
whereas the get
means to redeem the value and name of the appends
with initials uppercase and finally Attribute
at the end, which is the default for access methods.
After doing the research observe 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 obtained data do not interfere with those that make relation with the database, do not disturb the formats that is used for example in a 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 in SQL
:
Leitura::select(\DB::raw("date_format(`data`,'%d/%m/%Y'),`nivel`"))
->where('estacao_id', $id)
->get();
Have you tried this way https://laravel.com/docs/4.2/eloquent#date-mutators ?
– Valdeir Psr
@Valdeirpsr Already yes. Mutators modify the format as the application inserts the information into the database, I would just like to change how it is displayed not how it is recorded. Thanks for the help.
– Marcel
I think you can find the solution to your problem here: https://answall.com/questions/321242/como-mudar-o-formato-serializa%C3%A7%C3%A3o-json-do-datetime-do-php/321270#321270
– Wallace Maxters