6

Migration

Schema::create('users', function (Blueprint $table) {
        $table->increments('user_id');
        $table->string('username',50)->unique();
        $table->date('start_date');
        $table->date('end_date')->nullable();
        $table->timestamps();
    });

Here start_date set as column type date and nullable

When running Insert function like below its inserting null values

$insert = [
    'username'  =>strtoupper(request('username')),
    'password'  =>Hash::make(request('password')),
    'start_date'  =>date('Y-m-d',strtotime(request('start_date'))),
  ];
  if(request()->filled('end_date')){
    $insert['end_date'] = date('Y-m-d',strtotime(request('end_date')));
  }
  User::create($insert);

enter image description here

When Updating the same row left blank as end_date input,

$user = User::GetWithEncrypted(request('user_id'));
$update ['start_date'] = date('Y-m-d',strtotime(request('start_date')));
if(request()->filled('end_date')){
  $update['end_date'] = date('Y-m-d',strtotime(request('end_date')));
}else{
  $update['end_date'] = 'NULL';
}
$user->update($update);

In Table, it comes like below enter image description here

How can I make it NULL like insert function in update? My strict mode is false now, If I make it true it will throw an exception of invalid data for the end_date column.

3 Answers 3

16

Try replacing

}else{
  $update['end_date'] = 'NULL';
}

with

}else{
  $update['end_date'] = null;
}

'NULL' is a string whereas null is truly null.

Sign up to request clarification or add additional context in comments.

Comments

0

you have 2 solution for this problem:

1.

$user = User::GetWithEncrypted(request('user_id'));
    $update ['start_date'] = date('Y-m-d',strtotime(request('start_date')));
    if(request()->filled('end_date')){
      $update['end_date'] = date('Y-m-d',strtotime(request('end_date')));
    }else{
      $update['end_date'] = '".date('00:00:00')."';
    }
    $user->update($update);

2. you have to set default in mysql database on end date field

enter image description here

Comments

0

First set table field to nullable()
Second set table field DEFAULT to NULL

Third:

$model->field = null;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.