首页 > 解决方案 > 使用 Carbon 将日期保存到数据库中

问题描述

我还是 Laravel 的新手。目前,我正在学习和研究 Carbon。我已经查看了所有文档和其他解决方案,但我仍然不明白。我希望有人可以逐步教我如何纠正或改进我的代码。

投诉控制器.php

public function store(Request $request)
    {
        if (count($request->defect_id) > 0) {
            foreach($request->defect_id as $item=>$v) {
                 $data = array(
                     'defect_id' => $request->defect_id[$item],
                     'image' => $filename,
                     'description' => $request->description[$item],
                     'report_by' => Auth::user()->id,
                     'created_at' => Carbon::today()->toDateString(),
                     'updated_at' => Carbon::now()->toDateTimeString()
                 );
                Complaint::insert($data);

created_at仅将字段保存为日期,没有时间,格式为(yy-mm-dd).

index.blade.php

<div class="panel-body">
   <table class="table table-hover">
        <thead>
        <tr>
            <th>Defect Name</th>
            <th>Description</th>
            <th>Image</th>
            <th>Report Date</th>
            <th>Due Date</th>
        </tr>
        </thead>
        @foreach($complaint as $c)
           <tr>
              <td>{{$c->defect->name}}</td>
              <td>{{$c->description}}</td>
              <td><img src="{{ Storage::url('complaint/' . $c->image)}}" class="" alt="{{$c->image}}"></td>
              <td>{{$c->created_at->toDateString()}}</td>
              <td></td>
           </tr>
        @endforeach
   </table>
</div>

我的日期仍然在表格中很好地显示,(yy-mm-dd)但我希望日期的格式为 ,(dd/mm/yy)所以我尝试使用这种代码{{$c->created_at->toDateString()->format("dd/mm/yy")}}并出现错误,即Call to a member function format() on string. 稍后,我需要为到期日期添加另一个字段并使用此功能addDays(30)。那么,我需要做什么?我猜我需要在我的模型中添加另一个函数,但我不知道该怎么做。

标签: phplaraveldate

解决方案


正如@Tim Lewis 所提到的,替换

{{ $c->created_at->toDateString()->format("dd/mm/yy") }}

{{ $c->created_at->format("dd/mm/yy") }}

AstoDateString()在更改格式之前将其转换为字符串。


您也可以尝试使用标准 php 格式的日期时间,而不是Carbon类,

{{ date("d/m/Y", strtotime($c->created_at)) }}  

至于您要添加新表数据列的第二个问题,

<tr>
  <td>{{ $c->defect->name }}</td>
  <td>{{ $c->description }}</td>
  <td><img src="{{ Storage::url('complaint/' . $c->image)}}" class="" alt="{{$c->image}}"></td>
  <td>{{ $c->created_at->format("dd/mm/yy") }}</td>
  <td>{{ $c->created_at->addDays(30)  }}</td>
</tr>

推荐阅读