Search code examples
phplaravelphp-carbon

Laravel Carbon data missing when date is an empty string


In my model I have the following:

protected $dates = ['start_date'];

I am using an input field of type 'date' to select the date. If the user removes the date, its value becomes a null string "". when updating my model, I get the following error:

exception: "InvalidArgumentException"
file: "C:\www\projects\crm\vendor\nesbot\carbon\src\Carbon\Carbon.php"
line: 582
message: "Data missing"

I can avoid this error by using a mutator like this:

public function setStartDateAttribute($value)
{
    if ($value) {
        $this->attributes['start_date'] = $value;
    } else {
        $this->attributes['start_date'] = null;
    }
}

Question: Is there a faster/better way than using a mutator to deal with storing an empty string as a date?


Solution

  • 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 to null. This helps you normalize the input for every request entering into your application and not have to worry about continually calling the trim 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]);