【问题标题】:laravel form model binding - date formattinglaravel 表单模型绑定 - 日期格式
【发布时间】:2014-07-04 11:34:57
【问题描述】:

我有 Laravel。我有一个表格。我有一个 MySQL 数据库。里面有一些日期。当我绑定模型和表单时,表单会忠实地填充原始 MySQL 日期。这显然不是我需要的。

我的问题是:如何让模型绑定表单以更易读的方式显示日期?!?没有机会拦截和格式化数据。或者对于更通用的解决方案,有没有办法在用户看到之前对模型和表单之间的任何数据进行一些处理?

我认为这一切都错了吗?十亿谢谢!

【问题讨论】:

标签: forms binding laravel model laravel-4


【解决方案1】:

您可以通过在模型中创建 Accessor 来格式化从数据库中检索到的所有字段。例如,如果您的数据库字段是created_at,请使用getCreatedAtAttribute

public function getCreatedAtAttribute($date)
{
    return Carbon::($date)->format('d/m/Y');
}

【讨论】:

    【解决方案2】:

    您可以像这样在模型中添加accessor 方法:

    public function getCreatedAtAttribute($date)
    {
        $date = new \Carbon\Carbon($date);
        // Now modify and return the date
    }
    

    这将为created_at 调用。如果您需要覆盖默认值,还请检查date-mutators。检查Carbon Docs

    【讨论】:

    • 我可以修改它以访问另一个字段吗?即:公共函数getMyOtherDateFieldAttribute($date){...
    • 是的,您只需在要修改的列之后命名函数。请务必在函数名称上使用驼峰式大小写。
    • 当数据字段名是start_dt时,函数名是什么。如 public function getStart_dtAttribute($date) {}。以及为什么它必须使用碳。
    • 应该是getStartDtAttribute@webtuts4u :-)
    • 嘿@"Trass Vasston",Accessor 将始终格式化日期,当您不想格式化它检索的每个案例时,这可能会让人头疼)!所以,我推荐@ollieread 的答案而不是使用访问器。
    【解决方案3】:

    您可以使用format() 方法格式化表单中的日期。

    如果您在表单元素中使用它:

    {{ Form::text('name', $model->created_at->format('d/m/Y H:i')) }}
    

    如果您将其显示为纯文本:

    {{ $model->created_at->format('d/m/Y H:i') }}
    

    如果您希望用户能够以一种很好的方式修改日期,您可以使用三个不同的选择字段。以下是我参与的一个允许用户更改出生日期的项目的摘录:

    <div class="form-group {{ $errors->has('date_of_birth') ? 'has-error' : '' }}">
        {{ Form::label('date_of_birth', 'Date of Birth', ['class' => 'control-label']) }}
        <div class="form-inline">
            {{ Form::selectRange('date_of_birth[day]', 1, 31, null, ['class' => 'form-control']) }}
            {{ Form::selectMonth('date_of_birth[month]', null, ['class' => 'form-control']) }}
            {{ Form::selectYear('date_of_birth[year]', date('Y') - 3, date('Y') - 16, null, ['class' => 'form-control']) }}
        </div>
        {{ $errors->first('date_of_birth', '<span class="help-block">:message</span>') }}
    </div>
    

    这包含在绑定了模型的表单中。

    旁注

    此处发布的替代答案实际上覆盖了 laravel 处理日期的默认方式,除非您实际返回碳对象,否则您将永远无法使用 format 方法或任何其他方便的东西那个碳有。

    如果您有其他包含日期的列,请将它们添加到数据修改器列表中:

    public function getDates()
    {
        return ['created_at', 'updated_at', 'date_of_birth', 'some_date_column'];
    }
    

    现在,这将使每个都是Carbon 的实例,让您可以随时随地进行格式化,并轻松修改、复制和一大堆其他内容。有关这方面的更多信息,请参阅:http://laravel.com/docs/eloquent#date-mutators

    【讨论】:

    • $date = new \Carbon\Carbon($date); 会产生一个Carbon 对象,$date 会因为new \Carbon\Carbon($date) 而变成一个Carbon 对象。在我的回答中,我提到了// Now modify and return the date
    • @WereWolf-TheAlpha 是的,但是如果您返回 Carbon 对象,那么它最终与仅使用 format() 相比并没有真正的好处。
    猜你喜欢
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    相关资源
    最近更新 更多