Format data before saving in bank

3

I am using Laravel to develop a system, but I have a problem with the data coming from a form, I need to format a data in the following format ( #. ## strong>) to perform certain calculations, the problem that the value comes with the following format ( ###. # ) making the final value go wrong, I do not know how I I can format this data in Controller or before sending it.

Follow the input code

<label for="peso">Peso (Kg) : </label>
<input type="text" name="peso" class="form-control" v-model="peso"/>
<label for="altura">Altura (m) : </label>
<input type="text" name="altura" class="form-control" v-model="altura" v-mask="'#.##'"/>
<br/>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" value="Enviar" class="btn btn-success pull-right"/>
<br>

Follow the controller code where I need to validate the data

public function store(ImcRequest $request)
{
    $imc = new Imc;
    $imc->peso = $request->peso;
    $imc->altura = $request->altura;
    $altura2 = ($imc->altura) * ($imc->altura);
    $imc->imccalculado = ($imc->peso / $altura2);

    if (($imc->imccalculado) < 16.00) {
        $imc->classificacao = 'Magreza severa';
    } elseif (($imc->imccalculado >= 16.00) && ($imc->imccalculado <= 16.99)) {
        $imc->classificacao = 'Magreza moderada';
    } elseif (($imc->imccalculado >= 17.00) && ($imc->imccalculado <= 18.40)) {
        $imc->classificacao = 'Magreza leve';
    } elseif (($imc->imccalculado >= 18.5) && ($imc->imccalculado <= 24.99)) {
        $imc->classificacao = 'Normal';
    } elseif (($imc->imccalculado >= 25.00) && ($imc->imccalculado <= 29.99)) {
        $imc->classificacao = 'Preobeso';
    } elseif (($imc->imccalculado >= 30.00) && ($imc->imccalculado <= 34.99)) {
        $imc->classificacao = 'Obesidade leve';
    } elseif (($imc->imccalculado >= 35.00) && ($imc->imccalculado <= 39.99)) {
        $imc->classificacao = 'Obesidade media';
    } elseif (($imc->imccalculado) >= 40.00) {
        $imc->classificacao = 'Obesidade morbida';
    }

    $imc->user_id = Auth::id();
    $imc->save();

    return redirect('/imcs');
}
    
asked by anonymous 22.09.2017 / 14:06

1 answer

1

Try to use:

$imc->peso = number_format($request->peso, 2, '.');
$imc->altura = number_format($request->altura, 2, '.');

Another gambiarra option:

$num = 100.4;
$num = str_replace('.', '', $num);
$num = str_replace(',', '', $num);
echo substr($num, 0, strlen($num)-2).".".substr($num, strlen($num)-2);

I think it's better to treat 3-digit numbers with an error message or mask on the form, but these are examples of gambiarras for treatment in controller . One tip, check how the data arrives at controller before, put a dd($request->campoX); at the beginning of the function code because the problem might be in some component loaded in the JS of the page as well.

    
24.10.2017 / 13:44