Welcome to Accessors and Mutators:
Proper way of doing this using Laravel is by defining an Accessor:
The accessor will automatically be called by Eloquent when attempting to retrieve the value of your fields.
This means that you don't have to loop over a set of objects and then convert the values, simply define an Accessor in your model and you're good to go.
Solution #1:
So for your date field add the following method to your Orders Model
public function getCreatedAtAttribute($value)
{
return $value->format('d/m/y H:i a');
}
The name of an Accessor should be getFieldAttribute
where you replace field with your corresponding column name.
This way you don't have to loop over the results.
Note:
do bare in mind that by doing so, you are now getting the created_at as a string not a Carbon object anymore in your model, so how can this affect you? if you're doing some comparison somewhere else, you can also use a Mutator to set the field value more on Accessors and Mutators can be found here https://laravel.com/docs/5.1/eloquent-mutators
Solution #2:
Yeap, basically loop over all of your array and do the conversion.
for($i = 0; $i < count($orders); $i++ ) {
$orders[$i]->created_at = $orders[$i]->created_at->format('d/m/y H:i a');
}
Update:
if you're experiencing errors like "The separation symbol could not be found" or "Unexpected data found."
adjust the solutions like this:
Solution #1:
public function getCreatedAtAttribute($value)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $value->toDateTimeString())->format('d/m/y H:i a');
}
Solution #2:
for($i = 0; $i < count($orders); $i++ ) {
$orders[$i]->created_at = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $orders[$i]->created_at->toDateTimeString())->format('d/m/y H:i a');
}