D
D
deleted-mezhevikin2015-05-22 19:26:30
Laravel
deleted-mezhevikin, 2015-05-22 19:26:30

How to properly work with timestamp/carbon in laravel5?

I make comments. In the Comment model, in addition to the standard created_at date, there is also the created_at_parent parent date.
I added to the Comment model, protected $dates = ['created_at_parent']; so that created_at_parent is a carbon object.
By default created_at_parent == created_at.
I create a Comment object, assign $comment->created_at to $comment->created_at_parent.

$comment = new Comment();
$comment->text = $request->get('text');
$comment->created_at_parent = $comment->created_at;
$comment->save();

And after saving I get dates with a difference of 3 hours. Although both Carbon.
If you do a preliminary parse through carbon, then everything is ok. Well, this is some kind of crutch
$comment = new Comment();
   $comment->text = $request->get('text');
   $comment->created_at_parent = Carbon::parse($comment->created_at);
   $comment->save();

How correctly to work with date in that case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
deleted-mezhevikin, 2015-05-22
@deleted-mezhevikin

The problem was that $comment->created_at was empty before the save() method was called;

$comment = new Comment();
$comment->text = $request->get('text');
$comment->created_at = Carbon::now();
$comment->created_at_parent = $comment->created_at;
$comment->save();

6
65536, 2015-05-22
@65536

I'm like this: $comment->created_at->toDateTimeString()
, in theory, you can write in the model
public function getCreated_atAttribute($value)
{
return $value->toDateTimeString();
}
then it will lead to this kind. but this is only if it is needed everywhere in this form

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question