I am trying to sum two numbers and save the result in the bank with Variable plus this giving error Undefined offset

Asked

Viewed 59 times

-3

public function somar(Request $req){

    $dados= $req->all();
    $n1=$_POST['n1'];
    $n2=$_POST['n2'];
    $resultado=$n1+$n2;
     Calculo::create([
        'resultado'=> $dados[$resultado], 
    ]);
    return redirect()->route('admin.calculadora');

}
  • See in your HTML if the input is with attribute name as n1 and N2

  • yes ta with the same names in html he ta catching the result until just know it’s something that’s missing there in the array

1 answer

0


John, there are some inconsistencies in the code:

In the first line you store in $data, all inputs that came in the request.

But on the second and third lines, you don’t use the $data array to extract your inputs from it. No problem, so far.

In the fourth line, you store in $result the sum value $n1 and $N2. A variable has been created ($result).

In the create method, you ask for data that does not even exist in the array. The $result index does not exist in the $data array. If you want to enter $results in the 'result' column, just do it :

Calculo::create([
        'resultado'=> $resultado, 
]);

Note that you didn’t even use the $data array. Maybe, the stream you were looking for was this :

$dados = $request->all();
$n1 = $dados['n1'];
$n2 = $dados['n2'];
$resultado = $n1 + $n2;

Calculo::create([
        'resultado'=> $resultado, 
]);

You can still make your code more objective.

$resultado = $request->input('n1') + $request->input('n2');

Calculo::create([
        'resultado'=> $resultado, 
]);

Hope I helped, hugs.

  • Thanks even guy helped me a lot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.