Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Carbon Data Missing

In my model I have the following:

protected $dates = [
    'start',
    'end',
    'created_at',
    'updated_at'
];

I am using a datetime picker to insert the start and end dates, in this format:

2016-01-23 22:00

Without the seconds. When I do it like this, I get this error:

InvalidArgumentException in Carbon.php line 425:
Data missing
at Carbon::createFromFormat('Y-m-d H:i:s', '2016-01-23 22:00') in Model.php line 3015

If I do include the seconds, it works. The seconds are not important to me, and I do not want to include them in my datetime picker fields. Any way around this so I can still use those fields as date fields?

like image 778
Hardist Avatar asked Jan 23 '16 19:01

Hardist


People also ask

Is Carbon included in Laravel?

In order to use Carbon, you'll need to import Carbon from the Carbon namespace. Luckily for us, Carbon is already included in Laravel.

How do you use Carbon function in Laravel?

Most web applications require to work with date and time. The web application developed by the Laravel framework uses a simple API extension to work with the date and time called Carbon. This PHP package can handle the time and timezone more easily in the Laravel project.

How do you convert a string to a Carbon date?

$date = Carbon\Carbon::parse($rawDate); well thats it. You'll now have a Carbon instance & you can format the date as you like using Carbon helper functions.


3 Answers

tl;dr

Your date string and your date format is different, you have to change the format string or modify the date string so they match.

Explanation

The Problem

This error arises when Carbon's createFromFormat function receieves a date string that doesn't match the passed format string. More precisely this comes from the DateTime::createFromFormat function, because Carbon just calls that:

public static function createFromFormat($format, $time, $tz = null) {     if ($tz !== null) {         $dt = parent::createFromFormat($format, $time, static::safeCreateDateTimeZone($tz));     } else {         $dt = parent::createFromFormat($format, $time); // Where the error happens.     }      if ($dt instanceof DateTime) {         return static::instance($dt);     }      $errors = static::getLastErrors();     throw new InvalidArgumentException(implode(PHP_EOL, $errors['errors'])); // Where the exception was thrown. } 

Not enough data

If your date string is "shorter" than the format string like in this case:

Carbon::createFromFormat('Y-m-d H:i:s', '2017-01-04 00:52'); 

Carbon will throw:

InvalidArgumentException in Carbon.php line 425:
Data missing

Too much data

If your date string is "longer" than the format string like in this case:

 Carbon::createFromFormat('Y-m-d H:i', '2017-01-02 00:27:00'); 

Carbon will throw:

InvalidArgumentException in Carbon.php line 425:
Trailing data

Under the hood

According to the documentation on mutators the default date format is: 'Y-m-d H:i:s'. The date processing happens in the Model's asDateTime function. In the last condition the getDateFormat function is called, thats where the custom format comes from. The default format is defined in the Database's Grammar class.

Solution

You have to make sure that the date string matches the format string.

Change the format string

You can override the default format string like this:

class Event extends Model {     protected $dateFormat = 'Y-m-d H:i'; } 

There is two problem with this approach:

  • This will apply to every field defined in the model's $dates array.
  • You have to store the data in this format in the database.

Edit and format the date strings

My recommended solution is that the date format should stay the default 'Y-m-d H:i:s' and you should complete the missing parts of the date, like this:

public function store(Request $request) {     $requestData = $request->all();     $requestData['start_time'] .= ':00';     $requestData['end_time'] .= ':00';     $event = new Event($requestData);     $event->save(); } 

And when you want to use the date you should format it:

public function show(Request request, $eventId) {     $event = Event::findOrFail($eventId);     $startTime = $event->start_time->format('Y-m-d H:i');     $endTime = $event->end_time->format('Y-m-d H:i'); } 

Of course the fields should be mutated to dates:

class Event extends Model {     protected $dates = [         'start_time',         'end_time',         'created_at',         'updated_at',         'deleted_at',     ]; } 
like image 121
totymedli Avatar answered Sep 22 '22 02:09

totymedli


Models

This function disabled, the emulations for carbon in Datetimes https://laravel.com/docs/5.0/eloquent#date-mutators

public function getDates() {     return []; } 
like image 30
Cristhian Carreño Avatar answered Sep 23 '22 02:09

Cristhian Carreño


You can set the $dateFormat in your model as Christian says, but if you don't want to imply the updated_at and created_at fields into the operation you can use events to "correct" the datetime object before saving it into the database.

Here you have the official doc about it: https://laravel.com/docs/5.2/eloquent#events

like image 35
subzeta Avatar answered Sep 22 '22 02:09

subzeta