senty
senty

Reputation: 12857

Adding Carbon in Model for custom timestamp

I have created my own timestamp (beside updated_at & created_at) in database and filled it with seeder. Example data looks like this:

| id  |user|start_at (my timetable)| |   created_at        | updated_at
| 194 | 47 | 2015-01-21 00:00:00 | | 2016-09-25 16:48:48 | 2016-09-25 16:48:48 |

Also I added in my Model:

public function getCreatedAtAttribute($date)
{
    return Carbon::createFromFormat('Y-m-d H:i:s', $date);
}

public function getUpdatedAtAttribute($date)
{
    return Carbon::createFromFormat('Y-m-d H:i:s', $date);
}

public function getStartAtAttribute($date)
{
    return Carbon::createFromFormat('Y-m-d H:i:s', $date);
}

Now I try in my Controller:

$val->updated_at->diffForHumans();  // works
$val->created_at->format('d M Y'); // works

$val->start_at->format('d M Y'); // doesn't work

When I var_dump:

start_at:
 public 'date' => string '2016-10-12 00:00:00.000000' (length=26)
 public 'timezone_type' => int 3
 public 'timezone' => string 'UTC' (length=3)

created_at:
  +"date": "2016-09-25 16:48:48.000000"
  +"timezone_type": 3
  +"timezone": "UTC"

Update: Now I added protected $dates = ['start_at']

dd($val->start_at); // gives '2014-08-03 00:00:00'
dd($val->start_at->format('d M Y') // fails

Error:

Unexpected data found. The separation symbol could not be found Data missing

Upvotes: 1

Views: 2993

Answers (2)

Akshay Deshmukh
Akshay Deshmukh

Reputation: 1292

Mentioned start_at as carbon inastamce.

In your model add following code

protected $dates = [
        'start_at ',
    ];

Hope this will work.

Upvotes: 1

Adiasz
Adiasz

Reputation: 1804

Add start_at to $dates attribute of your model. You need to write custom setters or getter for this neither for created_at or updated_at attributes.

protected $dates = [
        'start_at',
    ];

Upvotes: 5

Related Questions