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

Juliver Galleto picture Juliver Galleto · Jun 22, 2016 · Viewed 39.5k times · Source

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.

Answer

Ohgodwhy picture Ohgodwhy · Jun 22, 2016

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 the updated_at.

public function getCreatedAtAttribute($timestamp) {
    return Carbon\Carbon::parse($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.