Hareesh
Hareesh

Reputation: 1577

Laravel 5.5 formatting the result in pluck method

I have the following code to get the date value in the (Y-m-d H:i:s) format. I need to get the value in (Y-m-d) format while retrieving. Is it possible to use a function in pluck method?

$dates = $this->collection->pluck('date');

Upvotes: 1

Views: 2946

Answers (2)

JeuneApprenti
JeuneApprenti

Reputation: 517

You can check Date Mutators and Carbon which is the approach choose by Laravel to format dates. You will need to have something like this in your model :

protected $dateFormat = 'd-m-Y';

And then, in the view when you simply loop over your collection and call {{ $dates }} it will display your date formatted in 'd-m-Y'.

Upvotes: 0

fubar
fubar

Reputation: 17378

You can use map() instead of pluck(), which will then allow you to modify the value returned as required:

// If $model->date is a DateTime object
$dates = $this->collection->map(function ($model) {
    return $model->date->format('Y-m-d');
});

// If $model->date is a string
$dates = $this->collection->map(function ($model) {
    return date('Y-m-d', strtotime($model->date));
});

Upvotes: 5

Related Questions