Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Is it possible to change the date format of an entire Collection?

If I have an instance of Illuminate\Support\Collection, which is data from a DB. And one of the columns is a date in the format of YYYY-mm-dd, is it possible to change the date format of the entire collection to dd-mm-YYYY?

Not while echoing it, but actually change it (so I can't use date_format, or the Carbon equivalent)

0 likes
8 replies
vincent15000's avatar

@Sinnbeck Sorry I didn't see your comment ;). I see that we have had the same idea, but I only have developed a bit more.

1 like
vincent15000's avatar

The better way is to cast the field in the model.

protected $casts = [
    'date_field' => 'date',
];

Then you can add a getter to retrieve the date transformed in your format.

public function getDateFieldAttribute()
{
        $date = Carbon::createFromFormat('Y-m-d', $this->date_field)->isoFormat('DD-MM-YYYY');
}

Why couldn't you use Carbon ? If it's really not possible, you can explode the date string and rewrite it.

$date_items = explode('-', $this->date_field);
$my_date = $date_items[2].'-'.$date_items[1].'-'.$date_items[0];
1 like
tykus's avatar

@Ligonsker

I am using raw query

Do you mean Query Builder? If you're working comfortable with formatting the date in the query, then that'd be easiest. The date format function will depend on your DBMS, e.g.

DB::table('table_name')->selectRaw('DATE_FORMAT(date_field, "%d-%m-%Y") as date' ) // remember other columns too
   // etc
 
2 likes
Ligonsker's avatar

@tykus Yes, I ended up doing:

FORMAT(date_col, 'dd-MM-yyyy')

Edit: Just saw your update. I guess I should also change my code to use DATE_FORMAT instead of FORMAT?

1 like

Please or to participate in this conversation.