Search code examples
laravellaravel-migrations

Laravel inserting data in SQL not possible cause of wrong use of functions


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');
        });
    }
}

Solution

  • The create() method saves the record immediately. You need to adjust your logic to make sure that hours is populated before calling that:

    public function addData(Request $request) {
      $checkin = Carbon::parse($request->checkintimestamp);
      $checkout = Carbon::parse($request->checkouttimestamp);
      $hours = $checkout->floatDiffInHours($checkin);
    
      return Time::create([
        'workers_workid' => $request->worker,
        'checkin' => $checkin,
        'checkout' => $checkout,
        'hours' => $hours
      ]);
    }
    

    Sidenote: Your saveData() method is redundant, and can be removed.

    There are other approaches, like $rec = new Time();, the adding the fields one-by-one, then calling save:

    public function addData(Request $request) {
      $time = new Time();
    
      $time->workers_workid = $request->worker;
      $time->checkin = Carbon::parse($request->checkintimestamp);
      $time->checkout = Carbon::parse($request->checkouttimestamp);
      $time->hours = $time->checkout->floatDiffInHours($time->checkin);
    
      $time->save();
    
      return $time;
    }