【问题标题】:briannesbitt/Carbon with Laravel Blade Templates - Formatting custom dateTime column带有 Laravel Blade 模板的 briannesbitt/Carbon - 格式化自定义日期时间列
【发布时间】:2015-02-25 10:05:47
【问题描述】:

我正在尝试在刀片视图中显示格式化的日期。我正在使用 Laravel 4.1。

我在config/app.php 中创建了一个别名

'Carbon'          => 'Carbon\Carbon'

我按如下方式迁移我的约会表:

$table->dateTime('appointment');

查看

@foreach($appointments as $appointment)
<tr>
        <td>{{{ $appointment->customer_name }}}</td> 
    <td>{{{ $appointment->consultant->consultant_name }}}</td>
    <td>{{{ $appointment->appointment }}}</td> {{-- Displays as seen in mysql --}}
    </tr>
@endforeach

如果我尝试如下格式化日期,则会引发异常:

<td>{{{ $appointment->appointment->format('Y-m-d') }}}</td>

Symfony \ Component \ Debug \ Exception \ FatalErrorException
Call to a member function format() on a non-object

如果我将{{{ $appointment-&gt;appointment-&gt;format('Y-m-d') }}} 更改为{{{ $appointment-&gt;created_at-&gt;format('Y-m-d') }}},则日期格式正确。

如何让 laravel 和 Carbon 将 appointment 处理和格式化为可以格式化的日期?

【问题讨论】:

  • 我想我可以让它工作......在我的Appointment 模型中,我覆盖getDates 方法如下:public function getDates() { return array('created_at', 'updated_at', 'deleted_at', 'appointment'); }
  • 是的,您需要将其添加到该数组中,以便将其转换为碳对象。您应该提交自己的答案并将其标记为答案。

标签: php datetime laravel


【解决方案1】:

在您的 Appointment 模型中添加属性

protected $dates = array('appointment');

这会被拾取并添加到被视为日期的默认字段(created_atupdated_atdeleted_at),然后自动转换为 Carbon 实例。

您可以改写 getDates 方法,正如您在评论中所建议的那样,但没有必要,因为您仍然希望所有默认字段都被视为日期。通过设置此属性,无需重复它们。见the source code for getDates

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 2016-03-24
    • 2017-04-21
    • 2016-02-28
    • 2016-12-01
    • 2018-03-13
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多