Carbon.php The separation symbol could not be found Data missing

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

First, I retrieve all the records,

//get inventory items $inv = inventory::all(); 

and then I loop on the retrieved records and modify the created_at and updated_at data to make it more human readable date.

foreach($inv as $i){     $i->created_at = date("M d, Y",strtotime($i->created_at));     $i->updated_at = date("M d, Y",strtotime($i->updated_at)); } 

but it returns me this error,

InvalidArgumentException in Carbon.php line 425: Unexpected data found. Unexpected data found. The separation symbol could not be found Data missing

any ideas, help, clues, suggestions, recommendations please?

here's my model

namespace App;  use Illuminate\Database\Eloquent\Model;  class inventory extends Model {     protected $table = "inventory";     protected $primaryKey = "item_id";     public $incrementing = false;      public function profile(){         return $this->belongsTo('App\profile','username');     }     public function inventory_images(){         return $this->hasMany('App\inventory_images','item_id');     } } 

and in blade, I can just use

{{ date("M d, Y",strtotime($i->created_at)) }}  {{ date("M d, Y",strtotime($i->updated_at)) }} 

and it work just fine.

回答1:

I think you're going about this the wrong way. The data in your database doesn't need to be more human readable, only the display that a human actually interacts with.

To solve this, we will create a custom accessor method that will apply to all calls for the created_at. You can recreate this for theupdated_at`.

public function getCreatedAtAttribute($timestamp) {     return $timestamp->format('M d, Y'); } 

Then when you call $model->created_at your attribute will return in that format.

If for some reason you absolutely need the date stored in that format, then you need to add an attribute to your model telling it that the timestamp columns should be formatted according to a specific type, such as:

protected $dateFormat = 'M d, Y'; 

Sidenote

The reason that Carbon is involved is that it is applied to all of the columns generated by $table->timestamps(), so the created_at and updated_at columns. Furthemore, if you add more columns in the model to the protected $dates = [] array, those will also automagically be handled by Carbon.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!