【问题标题】:Laravel 5.5 formatting the result in pluck methodLaravel 5.5 在 pluck 方法中格式化结果
【发布时间】:2018-07-24 14:21:11
【问题描述】:

我有以下代码来获取 (Y-m-d H:i:s) 格式的日期值。我需要在检索时以 (Y-m-d) 格式获取值。是否可以在 pluck 方法中使用函数?

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

【问题讨论】:

标签: php laravel-5


【解决方案1】:

您可以检查 Date MutatorsCarbon 这是 Laravel 选择的格式化日期的方法。 你需要在你的模型中有这样的东西:

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

然后,当您简单地遍历您的收藏并调用 {{ $dates }} 时,它会在视图中显示您的日期,格式为“d-m-Y”。

【讨论】:

  • Collection 上调用pluck 将返回Collectionstrtotime 需要一个字符串值,而不是 Collection
【解决方案2】:

您可以使用map() 代替pluck(),这样您就可以根据需要修改返回的值:

// 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));
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2019-05-10
    • 2010-10-16
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    相关资源
    最近更新 更多