Search code examples
phplaravellaravel-7laravel-6.2

Convert time in laravel from 2 inputs


I am beginner in Laravel. I use in my project Laravel 6. I have 2 inputs:

<input maxlength="5" type="text" name="hours_worked" class="form-control edited valid" value="" required="" onkeypress="return isNumberKey(event)">

<input type="text" name="minutes_worked" class="form-control edited valid" value="" required="" onkeypress="return isNumberKey(event)">

I save to db with this code:

WorkingTime::create( $this->request->all()

I have a problem when someone types in the field, for example. "90" minutes. I have 90 minutes saved in the database - and I would like to save 1h and 30 minutes.

How can I achieve this with my code?

My schema:

Schema::create('working_times', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('client_id')->unsigned();
            $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
            $table->integer('case_id')->unsigned();
            $table->foreign('case_id')->references('id')->on('case_instances')->onDelete('cascade');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->smallInteger('hours_worked');
            $table->smallInteger('minutes_worked');
            $table->string('name');
            $table->string('appearance')->nullable();
            $table->longText('description')->nullable();
            $table->softDeletes();
            $table->timestamps();
        });

Solution

  • This is a crude solution, but instead of doing:

    WorkingTime::create($this->request->all());
    

    Do:

    $data = $this->request->all();
    $hours = (int) $data['hours_worked'];
    $minutes = (int) $data['minutes_worked'];
    $overMinutes = $minutes % 60;
    $hours += (int) (($minutes - $overMinutes) / 60);
    $minutes = $overMinutes;
    
    $data['hours_worked'] = $hours;
    $data['minutes_worked'] = $minutes;
    
    WorkingTime::create($data);