skip to Main Content

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', 'AppHttpControllersHomeController@get_form');
Route::post('/form', 'AppHttpControllersHomeController@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>

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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;
    ?>
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search