问题
I'm trying to pass a variable from one view to a controller to another view. I'm not getting any errors, but when it gets to the last view, it doesn't show the variable like it's supposed to. In the first view, I'm just getting a name.
{{ Form::open(array('route' => 'form', 'method'=>'post')) }}
{{ $name = Form::text('name') }}
{{ Form::submit('Go!') }}
{{ Form::close() }}
Here is my HomeController.php.
public function view1()
{
return View::make('stuff');
}
public function postView1($name)
{
return Redirect::route('view2')->with($name);
}
public function view2($name)
{
return View::make('view2')->with($name);
}
routes.php
Route::get('/', array('as' => 'stuff', 'uses' => 'HomeController@stuff'));
Route::post('form/{name}', array('as' => 'form', 'uses'=>'HomeController@postView1'));
Route::get('view2/{name}', array('as' => 'view2', 'uses' => 'HomeController@view2'));
view2.blade.php
{{ $name = Input::get('name') }}
<p> Hello, {{ $name }} </p>
So why isn't it showing up?
回答1:
First you should change your postView
function into:
public function postView1()
{
return Redirect::route('view2', ['name' => Input::get('name')]);
}
And your route:
Route::post('form/{name}', array('as' => 'form', 'uses'=>'HomeController@postView1'));
into:
Route::post('form', array('as' => 'form', 'uses'=>'HomeController@postView1'));
Now, you should change your view2
function into:
public function view2($name)
{
return View::make('view2')->with('name',$name);
}
Now in your view2.blade.php
you should be able to use:
<p> Hello, {{ $name }} </p>
回答2:
You need to name the variable:
public function view2($name)
{
return View::make('view2')->with('name', $name);
}
回答3:
class HomeController extends Controller {
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
}
public function index()
{
$data = array (
'title'=>'My App yo',
'Description'=>'This is New Application',
'author'=>'foo'
);
return view('home')->with($data);;
}
}
回答4:
Here's what other answers are missing, straight from Laravel docs:
Since the with method flashes data to the session, you may retrieve the data using the typical Session::get method.
So instead of {{$name}}
write {{Session::get('name')}}
.
回答5:
Try form will be if you using POST method why setting variable in route it will get directly on your function with post data.
{{ Form::open(array('url' => 'form', 'method'=>'post')) }}
{{Form::text('name') }}
{{ Form::submit('Go!') }}
{{ Form::close() }}
route :-
Route::post('form','HomeController@postView1');
controller function :-
public function postView1() {
$data = Input::all();
return Redirect::route('view2')->with('name', $data['name']);
}
and get data on view2 :-
<p> Hello, {{ $name }} </p>
For more follow HERE
来源:https://stackoverflow.com/questions/26353030/passing-variable-from-controller-to-view-laravel