Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a timestamp variable column in a mysql database. Trying to convert a carbon timestamp to something that I can input there, but Carbon::now() only returns a Carbon object and when I try to use the timestamp string of the Carbon object, it does not register in mysql.

public function store(CreateArticleRequest $request){
        $input = $request->all(); 
        var_dump($input); // JUST SO YOU CAN SEE
        $input['published_at'] = Carbon::now(); 
        var_dump($input); // JUST SO YOU CAN SEE
        Article::create($input);   
}

My first var dump is like so:

array (size=4)
  '_token' => string 'Wy67a4hWxrnfiGz61wmXfYCSjAdldv26wOJiLWNc' (length=40)
  'title' => string 'ASDFasdf' (length=8)
  'body' => string 'asdfasdf' (length=8)
  'published_at' => string '2015-08-26' (length=10)  

My second var dump is like so.

The mysql column relating to "published_at" is a timestamp variable. How an I suppose to convert this from a Carbon Object?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
360 views
Welcome To Ask or Share your Answers For Others

1 Answer

The short answer is that toDateTimeString() is what you're looking for:

$input['published_at'] = Carbon::now()->toDateTimeString();

See http://carbon.nesbot.com/docs/ for more options, including toDateString() if you just want the date part and not the time.

But an even better way to handle it would be to let Laravel handle casting the date value to/from a Carbon object for you. See https://laravel.com/docs/5.4/eloquent-mutators#date-mutators.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...