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
try using this code
define
$sum
param and pass to view to avoid theundefined $sum
errorIt’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.
Adendum
Remove the source code below from your blade View file as well.