简体   繁体   中英

Laravel 5.1 Format date BEFORE being put in array inside controller

I have the following code in my controller:

$gecko_id = Gecko::where(compact('user_id', 'name'))->first()->id; 
$weight = Weight::where(compact('user_id', 'gecko_id'))->orderBy('weighed_date', 'desc')->take(7)->get()->reverse();
$gecko = Gecko::where(compact('user_id', 'name'))->first();

return view('gecko.show')
    ->with('gecko', $gecko)
    ->with('dates', $weight->lists('weighed_date'))
    ->with('amounts', $weight->lists('gecko_weight'));

Which is sending data to my view for a chart i'm plotting. My dates list is outputting the following data format:

["2015-06-01","2015-05-01","2015-04-01","2015-03-01","2015-02-01","2015-01-01"]

Ideally I would like to format this before it is passed to the view so it's more readable. So say 2015-06-01 would be be reformatted into 01/06/2016 - I know how to do this in the usual PHP way, but because I'm putting the data into an array, I'm unsure on the best way of achieving my goal.

You can archive this by writing an accessor in your model. Accessors & Mutators .

For example:

class Weight extends Model{
    ...
    public function getWeighedDateAttribute($value){
        return Carbon\Carbon::parse($value)->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