Laravel not updating null values to column
Asked Answered
T

3

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.

Tui answered 5/12, 2018 at 11:43 Comment(0)
V
16

Try replacing

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

with

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

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

Vinegar answered 5/12, 2018 at 13:10 Comment(0)
L
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

Lagan answered 5/12, 2018 at 12:29 Comment(0)
T
0

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

Third:

$model->field = null;
Tristichous answered 6/3, 2021 at 8:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.