I was trying to calculate the time difference between check-in and checkout, but somehow it's not working. I'm pretty sure I'm doing something wrong, but I can't wrap my head around it.
SQLSTATE[HY000]: General error: 1364 Field 'hours' doesn't have a default value (SQL: insert into
times
(workers_workid
,checkin
,checkout
) values (110001, 2022-03-09T18:22, 2022-03-09T23:22))
Controller
class TimeController extends Controller
{
function addData(Request $req)
{
$time = new Time;
$time->workers_workid = $req->worker;
$time->checkin = $req->checkintimestamp;
$time->checkout = $req->checkouttimestamp;
$time->save();
$time->hours = $this->saveData($this->worker, $this->checkintimestamp,
$this->checkouttimestamp);
$time->save();
}
public function saveData($id, $cIn, $cOut)
{
$rec = Time::create([
'workers_workid' => $id,
'checkin' => Carbon::parse($cIn),
'checkout' => Carbon::parse($cOut),
]);
$rec['hours'] = $rec['checkout']->floatDiffInHours($rec['checkin']);
$rec->save();
return $rec;
}
}
Migration
class CreateTimesTable extends Migration
{
public function up()
{
Schema::create('times', function (Blueprint $table) {
$table->id();
$table->integer('workers_workid')->unsigned()->nullable();
$table->dateTime('checkin');
$table->dateTime('checkout');
$table->float('hours');
$table->foreign('workers_workid')
->references('workid')
->on('workers')
->onDelete('cascade');
});
}
}