If the end user does not use the "total time" data, I would suggest hiding it from the form. To do what you want in PHP you can use the "Carbon" library that is already included in Laravel.
You import the class;
use Carbon\Carbon;
In your role you put the following:
public function unaFuncion(Request $request){
$hora_inicial = new Carbon($request->hora_inicial);
$hora_final = new Carbon($request->hora_final);
$duracion = $hora_final->diff($hora_inicial)->format('%H:%i:%s');
}
You should make the most of what the framework already brings.
Now that if you want to keep the total time input, you can calculate the difference with javascript (using jQuery and moment.js) in the following way:
$(document).ready(function(){
calcularTiempo();
});
function calcularTiempo(){
//Tomando en cuenta que solo hay un input con esos nombres en el formulario
$('input[name=hora_inicio], input[name=hora_final]').on('change', function(e){
var valorInicio = $.trim($("input[name=hora_inicio]").val());
var valorFinal = $.trim($("input[name=hora_final]").val());
//Comprobar que si haya valores en ambos campos para poder validar y calcular
if(valorInicio != '' && valorFinal != ''){
//Validar el formato correcto del tiempo (HH:mm - 22:05)
if(!validarHMS(valorInicio) || !validarHMS(valorFinal)){
//alertar al usuario que los datos no son válidos
return false;
}
//crear formato de fecha
tiempoInicial = moment(valorInicio, "hh:mm");
tiempoFinal = moment(valorFinal, "hh:mm");
var total = moment(tiempoFinal.diff(tiempoInicial)).format("hh:mm");
$('#tiempo_total').val(total);
}
});
}
function validarHMS(valor) {
var esValido = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(valor);
return esValido;
}
If I strongly recommend the addition of the moment.js
library for handling issues of dates and times, it makes things much easier for you.
Similarly, if you keep the total time input in your form, you will have to re-calculate in PHP because anyone could modify the input.