Laravel Carbon Data Missing
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',
];
}
Data missing error when using Carbon::createFromFormat in laravel [dateFormat: year-month]
solution:
do some changes in ajax
data: {
site: site,
startdate: startdate,
},
xhrFields: {
responseType: 'blob' // to avoid binary data being mangled on charset conversion
},
success: function(blob, status, xhr) {
var ieEDGE = navigator.userAgent.match('/Edge/g');
var ie = navigator.userAgent.match('/.NET/g'); // IE 11+
var oldIE = navigator.userAgent.match('/MSIE/g');
if (ie || oldIE || ieEDGE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var fileURL = URL.createObjectURL(blob);
document.write('<iframe src="' + fileURL + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>');
}
},
error: function(data) {
alert('Error');
}
remove dataType:"json";
and replace it with xhrFields: { responseType: 'blob'}
then it works
Laravel Carbon data missing when date is an empty string
Looking into this a bit deeper:
Middleware updated in 5.4
Laravel 5.4 included two new middleware in the default middleware stack: TrimStrings
and ConvertEmptyStringsToNull
.
These middleware will automatically trim request input values and
convert any empty strings tonull
. This helps you normalize the
input for every request entering into your application and not have to
worry about continually calling thetrim
function in every route and
controller.
From: https://laravel.com/docs/5.4/releases#laravel-5.4
So, when I am grabbing the request object, an empty date field is converted to null. The database allows null on these fields and everything works correctly.
So, through the front end, date fields can be entered and removed without error. When updating manually to an empty string as per your request
\App\Yourmodel::find(7)->update(["your_date_field" => ""]);
I had the same data missing
error.
Question is, do you specifically need to pass an empty string or is making the field nullable a better option for you?
\App\Yourmodel::find(7)->update(["your_date_field" => null]);
Laravel : InvalidArgumentException in Carbon.php line 425: Data missing
Just remove 'tglkop', 'tglp3'
from your $casts
array, and add this to '$dates'
array. These properties will be automatically converted to Carbon
instances
UPDATE
I guess that your db columns tglkop
and tglp3
have DATE
type instead of DATETIME
.
This error
Carbon::createFromFormat('Y-m-d H:i:s', '10-12-2016') in blah blah blah
says that Carbon
expects date with format Y-m-d H:i:s
but you gives date in format d-m-Y
(10-12-2016
)
Solution 1:
change type of these columns to DATETIME
Solution 2:
add that in your model
protected $dateFormat = 'Y-m-d'; // this is expected format for `MySQL` `DATE` type field
UPDATE 2
I think you tries to create row in database. What data are you trying to pass into? I think tglkop
and tglp3
fields in your input have wrong format.
Laravel Carbon error data missing with casting
I have found the ability of use mutators for set attributes
public function setDateAttribute($date)
{
$this->attributes['date'] = Carbon::make($date);
}
https://laravel.com/docs/5.7/eloquent-mutators#defining-a-mutator
Related Topics
How to Remove <Br /> Tags and More from a String
Best Way to Initialize (Empty) Array in PHP
JSON VS. Serialized Array in Database
PHP Sending Variables to File_Get_Contents()
Removing Password from Rsa Private Key
Multi Dimensional Array in Random Order
Pdo: Call to a Member Function Fetch() on a Non-Object
How to Check If a User Is Logged-In in PHP
Laravel Eloquent Orm Transactions
Download of .Zip File Runs a Corrupted File PHP
Adding 1 Day to a Datetime Format Value