Why do I always get Undefined variable $var
error? I'm trying to work with one view only (my_view.blade.php
) but for some reason, when I navigate to http://127.0.0.1:8000/
I get the aforementioned error.
My intention's to make the $var
variable available in the view so I can use it in the blade file. This variable gets populated only when the user enters text and submits but for some reason, I can't even get to part where I can see the text input field because this file gets thrown upon loading the view. If I get rid {{ $var }}
, everything works as intended.
I thought this whole time I'm doing it correctly in terms of passing a variable to the view. What am I doing wrong?
controller:
public function addVar(Request $request) {
$var = $request->get('var');
Url::create([
'var' => $var
]);
view('my_view', compact('var'));
return Redirect::back();
}
web.php:
Route::get('/', function () {
return view('my_view');
});
Route::post('/add-var', [MyController::class, 'addVar'])->name('add-var');
my_view.blade.php:
{{ $var }}
<form method="POST" action="{{ route('add-var') }}">
{{csrf_field()}}
<input type="text" name="var" placeholder="Enter text"/>
<button type="submit" >Submit</button>
</form>
CodePudding user response:
If you wanna the two routes do the same thing
In web.php
:
Route::get('/', [MyController::class, 'addVar']);
Route::post('/add-var', [MyController::class, 'addVar'])->name('add-var');
In my_view.blade.php
:
{{ $var ?? '' }}
<form method="POST" action="{{ route('add-var') }}">
{{csrf_field()}}
<input type="text" name="var" placeholder="Enter text"/>
<button type="submit" >Submit</button>
</form>
CodePudding user response:
can you change
$var = $request->get('var');
to
$var = $request->var;