1

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');
Hareesh
  • 1,507
  • 3
  • 21
  • 43
  • Is the `date` attribute a `DateTime` instance, or a string? – fubar Feb 14 '18 at 05:03
  • Possible duplicate of [change the date format in laravel view page](https://stackoverflow.com/questions/40038521/change-the-date-format-in-laravel-view-page) – JeuneApprenti Feb 14 '18 at 05:08

2 Answers2

5

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));
});
fubar
  • 16,918
  • 4
  • 37
  • 43
0

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'.

JeuneApprenti
  • 489
  • 3
  • 20
  • 1
    Calling `pluck` on a `Collection` will return a `Collection`. `strtotime` expects a string value, not a `Collection`. – fubar Feb 14 '18 at 05:21