Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rocordial's avatar

Store model with empty date fields coming from forms.

I have a Contract model that has date_start and date_stop fields. If I know the duration of the contract the date_stop will be filled otherwise not.

I use HTML 5 date fields in form and if the date_stop is not filled it returns ''.

I also use protected $dates = ['date_start', 'date_stop', ....]; in the model.

If I try to create the Contract model I receive an error from Carbon that tries to parse my null date:

InvalidArgumentException in Carbon.php line 414: Data missing in Carbon.php line 414 at Carbon::createFromFormat('Y-m-d H:i:s', '') in Model.php line 2959 at Model->asDateTime('') in Model.php line 2479 at Model->attributesToArray() in Model.php line 2456 at Model->toArray() in AppServiceProvider.php line 25 at AppServiceProvider->App\Providers{closure}(object(Contract)) at call_user_func_array(object(Closure), array(object(Contract))) in Dispatcher.php line 221 at Dispatcher->fire('eloquent.saved: App\Contract', array(object(Contract))) in Model.php line 1694 at Model->fireModelEvent('eloquent.saved: App\Contract', false) in Model.php line 1531 at Model->finishSave(array()) in Model.php line 1517 at Model->save() in Model.php line 546 at Model::create(array('_token' => 'buE5IDxOFzs0lrSmJ9bCJescJhXdM6nSuSP2KPAp', 'angajat_id' => '1993', 'data_contract' => '2017-01-30', 'firma_id' => '7', 'echipa_id' => '54', 'data_inceput' => '2017-01-30', 'perioada' => 'nedeterminata', 'data_sfarsit' => '', 'data_incetare' => '', 'ocupatie_id' => '1', 'ore_sapt' => '35', 'zile_sapt' => '5', 'zile_co' => '40', 'data_efecte' => '2017-01-30', 'save' => 'Save')) in AngajatiContracteController.php line 62 at AngajatiContracteController->store(object(Request), '{angajati}')

Is there a solution for this or I shoud initialize the null dates from forms before Contract::create(...)?

Thank you!

0 likes
4 replies
safiahmed4cs@gmail.com's avatar

@rocordial

Before updating/creating you can check the condition in a boot method inside a model file

for example - you have to check with the condition whether the date is empty or not before calling carbon function.

Let me know if you face any issue

sherwinmdev's avatar

@rocordial you can use $request->has(). something like

$date_start = NULL;
if ($request->has('date_start')) {
    $date_start = Carbon::createFromFormat('Y-m-d H:i:s', $request->date_start);
}

// then in your insert
$foo->date_start            = $date_start;

assuming your date_start column in the database accepts nulls.

rocordial's avatar

Thank you guys!

I was thinking if Laravel provides an elegant, (almost) out of the box solution for that. That is accepting a date or null without throwing an error, something like the

protected $dates = [...];

is to turn a field into a Carbon instance.

Than, if I want to validate the date to not be null I can do so.

nolros's avatar

@rocordial

1 when you create the DB I assume you are using timestamps():

   public function up()
    {
        Schema::create('messages', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('name');
            $table->string('email')->index();
            $table->timestamps();
        });
    }

2 In your model ensure you have

protected $dates = [...];

3 Here is an example of a date helper:

<?php
    namespace Infrastructure\Services;


    use Carbon\Carbon;

    class DateTimeHelper
    {

        /**
         * Subtract twp dates from one another and then render to human readable format
         *
         * @param   Carbon $startDate
         * @param   Carbon $endDate
         * @return  string
         */
        public function dateDifferenceToHuman(Carbon $endDate, $startDate = null)
        {
            if (is_null($startDate))
            {
                $startDate = Carbon::now();
            }

            return ($endDate->diff($startDate)->days < 1)
                ? 'today'
                : $endDate->diffForHumans($startDate);
        }

        /**
         * Format a timestamp to a date
         *
         * @param $timeStamp
         * @return bool|string
         */
        public function dateFormat($timeStamp)
        {
            return date('Y-m-d h:i:s', $timeStamp);
        }

        /**
         * Create carbon date from timestamp e.g. file getCTime
         *
         * @param $timeStamp
         * @return static
         */
        public function createFromTimestamp($timeStamp)
        {
            return Carbon::createFromTimestamp($timeStamp);
        }



        /**
         * Subtract number of days from a timestamp
         *
         * @param $timestamp
         * @param $days
         * @return static
         */
        public function subDays($timestamp, $days)
        {
            return Carbon::createFromTimestamp($timestamp)->subDays($days);
        }

        /**
         * Timestamp to string for storage
         *
         * @param $timeStamp
         * @return string
         */
        public function createFromTimestampToStr($timeStamp)
        {
            Carbon::parse( $timeStamp)->toFormattedDateString();

            return Carbon::createFromTimestamp($timeStamp)->toDateTimeString();

        }



        /**
         * Get a Carbon timestamp and get difference from 2nd date, now can be any date
         *
         * @param $carbonNow
         * @param $carbonDate
         * @return mixed
         */
        public function daysDiff($startDate, $endDate)
        {
            return Carbon::parse($endDate)->diff(Carbon::parse($startDate))->days;
        }

        /**
         * Get a Carbon timestamp and get difference from 2nd date in human format, now can be any date
         *
         * @param $carbonNow
         * @param $carbonDate
         * @return mixed
         */
        public function daysDiffForHumans($startDate, $endDate)
        {
            return Carbon::parse($endDate)->diffForHumans(Carbon::parse($startDate));
        }



    }

4 Example of Carbon date query

                   Analytics::whereIn('category', $this->analyticDefinitionCategories)
                                ->where('analyticable_type', QuestionOption::class)
                                ->with([
                                        'months' => function($query) {
                                            $query->where('start_date', ">=", Carbon::now()->subMonth(2)->endOfMonth())
                                                ->where('end_date', "<=", Carbon::now()->addMonth(1)->startOfMonth());
                                        }])
                                    ->get() ) 

Please or to participate in this conversation.