php - Return a variable from a function to a view
I am a newbie in laravel 4 and want to return, when pressing a button, a value from a controller to the view.
My form view:
{{ Form::submit('Save', array('class' => 'btn btn-small btn-info iframe')) }}
<?php
echo $test;
?>
My Controller:
<?php
class TestController extends BaseController {
/**
* Start scrapping script.
*/
public function postTest() {
$scrap = 'It works!';
return View::make ( 'admin/test/index' )->with('test', $test);
}
}
My routes:
Route::post('test', '[email protected]');
However, I get:
Undefined variable: test(View: C:\xampp\htdocs\laravel_project\lara\app\views\admin\test\index.blade.php)
Any recommendations what I am doing wrong?
I appreciate your answer!
UPDATE
I now changed my controller like that:
public function getIndex() {
// Show the page
return View::make ( 'admin/test/index' );
}
public function postTest() {
$test = 'It works!';
return View::make ( 'admin/test/index' )->with('test', $test);
}
}
and added to my routes file:
Route::get('test', '[email protected]');
Route::post('test', '[email protected]');
Route::controller('test', 'TestController');
Furthermore, when calling:
{{ $test}}
I getUndefined variable: $test
Any recommendations what I am doing wrong?
Answer
Solution:
You should change in your controller:
to:
Now you are getting undefined warning because there is no
$test
variable in controller.And in Blade view, you should display it using:
or
(the second one for escaping characters) and not
<?php echo $test; ?>
Answer
Solution:
change to the following:
Answer
Solution:
Change your make to:
Additionally, if you look at your controller, the variable you give a value to is called $scrap while the one you assign to the view is called $test, I think you mean to give them both the same name (or else it will always be empty on the view).
Answer
Solution:
Also, in your view, make sure you check that
$test
is actually present.OR (as per your edit) change getIndex to:
to avoid the undefined variable issue.