[英]Passing variable from controller to view - Laravel
我正在嘗試將變量從一個視圖傳遞到控制器到另一個視圖。 我沒有得到任何錯誤,但是當它到達最后一個視圖時,它不會顯示它應該的變量。 在第一個視圖中,我只是得到一個名字。
{{ Form::open(array('route' => 'form', 'method'=>'post')) }}
{{ $name = Form::text('name') }}
{{ Form::submit('Go!') }}
{{ Form::close() }}
這是我的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>
那為什么不出現呢?
首先,您應該將postView
功能更改為:
public function postView1()
{
return Redirect::route('view2', ['name' => Input::get('name')]);
}
你的路線:
Route::post('form/{name}', array('as' => 'form', 'uses'=>'HomeController@postView1'));
成:
Route::post('form', array('as' => 'form', 'uses'=>'HomeController@postView1'));
現在,您應該將view2
函數更改為:
public function view2($name)
{
return View::make('view2')->with('name',$name);
}
現在在view2.blade.php
你應該可以使用:
<p> Hello, {{ $name }} </p>
您需要命名變量:
public function view2($name)
{
return View::make('view2')->with('name', $name);
}
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);;
}
}
如果您使用POST方法嘗試表單,為什么在路由中設置變量,它將直接在您的函數上使用post數據。
{{ Form::open(array('url' => 'form', 'method'=>'post')) }}
{{Form::text('name') }}
{{ Form::submit('Go!') }}
{{ Form::close() }}
路線: -
Route::post('form','HomeController@postView1');
控制器功能: -
public function postView1() {
$data = Input::all();
return Redirect::route('view2')->with('name', $data['name']);
}
並獲取view2上的數據: -
<p> Hello, {{ $name }} </p>
更多關注此處
以下是Laravel文檔中缺少的其他答案:
由於with方法將數據閃爍到會話,因此您可以使用典型的Session :: get方法檢索數據。
因此,而不是{{$name}}
寫{{Session::get('name')}}
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.