简体   繁体   中英

How to format a date in Laravel using ::lists

I am coding a feature in Laravel where a user can use a select box to choose a certain date. By standard, these dates are saved in ymd in my table.

I have succeeded in formatting the date to dd/mm/yyyy by using the Eloquent solution, adding to my Eloquent Model called Dataslot:

protected $dates = ['maand'];

Afterwards I could use the following to format the date.

     $d = Dataslot::find(1);
     $dformat = $d->maand->format('d-m-Y');

In order to pass the ID of the dataslot and the date to my select box, I have chosen to use the lists method.

$dataslots = Dataslot::lists("maand","id");

This returns me an array. I cannot use the format method on this array as I could on the object in the first example.

How can I have an array of formated dates, with the ID as a key, to send to my view?

Untested (I'm on mobile right now) but this should work;

Carbon::setToStringFormat('d-m-Y');
$dataslots = Dataslot::lists('maand', 'id');

You could change Carbon back after with:

Carbon::resetToStringFormat();

Would this do it?

$dataslots = Dataslots::all()->map(function($dataslot) {
    return [$dataslot->id => $dataslot->maand->format('d-m-Y')];
});

this did the trick:

$dataslots = Dataslot::all();

foreach ($dataslots as $o) {
    $flatArray[$o->id] = $o->maand->format('d-m-Y'); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM