format iso date from sql database and return to blade

SQL stores date as iso y-m-d

With:

Carbon\Carbon::parse($data[0]->date)->format('j F Y');

I can format the date to -> in the format 7 July 2018

However, i want to edit each date in the entire collection obtained

from $data= Data::where('id',$id)->get();

This will then be saved to the collection and showed in blade. Would you use a for loop ?

1 answer

  • answered 2018-07-17 23:28 Devon

    Laravel's query builders always return a collection when you use get().

    Laravel provides a lot of collection methods you can make use of on these. A good method for transforming data is map.

    $data = $data->map(function($item) {
        // Do any transformation to $item and return it
        $item->date = Carbon::parse($item->date)->format('j F Y');
        return $item;
    });
    

    Of course, with programming, there are often multiple ways to accomplish the same task. A simple foreach loop would do as well:

    foreach($data as $item) {
        $item->date = Carbon::parse($item->date)->format('j F Y');
    }
    

    This works well with objects since objects are always passed by reference. So you can make changes to the object and it will persist in the original collection.