Home > front end >  Sum 2 number with textbox / Laravel Php
Sum 2 number with textbox / Laravel Php

Time:09-13

I have shared the MVC structure below. I can't understand why I am getting this error:

Error: Undefined variable $sum

Controller:

public function get_form(){
    return view('form');
}

public function post_form(Request $request){
    $first=$request->first;
    $second=$request->second;
    $sum=$first   $second;
    return view('form')->with('sum',$sum);
}

Web.php:

Route::get('/form', 'App\Http\Controllers\HomeController@get_form');
Route::post('/form', 'App\Http\Controllers\HomeController@post_form');

form.blade.php:

    {{ $sum }}
<html>
    <?php
    $sum=0;
    ?>
    <form action="" method="POST">
        {{ csrf_field() }}
        <input type="text" name="first"> 
        <input type="text" name="second"> 
        <input type="submit"> 
    </form>
</html>

CodePudding user response:

ERROR: Undefined variable $sum

It's throwing that error because initially before the summation HTTP request is made, the View's rendered $sum variable is undefined.

It only gets defined on the second View render session after the input fields have been filled and a form submission has been made.

Solution

In your blade View.

{{$sum ?? 0}}

Adendum

Remove the source code below from your blade View file as well.

<?php
$sum = 0;
?>

CodePudding user response:

try using this code

public function get_form(){
    $sum = 0;
    return view('form', compact('sum'));
}

define $sum param and pass to view to avoid the undefined $sum error

  • Related