0712-2888027 189-8648-0214
微信公眾號

孝感風(fēng)信網(wǎng)絡(luò)科技有限公司微信公眾號

當(dāng)前位置:主頁 > 技術(shù)支持 > PHP > Laravel控制器Controller傳值到視圖View的幾種方法總結(jié)

Laravel控制器Controller傳值到視圖View的幾種方法總結(jié)

時間:2024-09-20來源:風(fēng)信官網(wǎng) 點擊: 1282次

從接觸編程,到 PHP,總共學(xué)習(xí)了三個月,剛接觸 laravel 框架沒多久
對于新人來說,感覺傳值有的時候看起來太迷惑。所以在這里整理一下,水平有限,也是第一次用 markdown 寫文檔有任何錯誤或者需要改進的地方請諸位悉心賜教。

 

總體內(nèi)容分為傳值類型和方法,大概總體感覺如下。

傳值類型:一個值,多個值,數(shù)組。
方法: with,view,compact
默認(rèn)視圖 test 文件下 index.blade.php

 

單個值的傳遞

 

with

public function index() {
  $test = "測試";
  return view('test.index')->with('test',$test);
}
 

view

public function index() {
    return view('test.index', ['test' => '測試']);
}
 

compact

public function index() {
  $test = "測試";
  return view('test.index',compact('test'));
}

 

多個值的傳遞

 

with

public function index() {
  return view('test.index')->with(["test1" => "測試1", "test2" => "測試2", "test3" => "測試3"]);
}
 

view

public function index() {
  return view('test.index', ['test1' => '測試1','test2' => '測試2','test3' => '測試3']);
}
 

compact

public function index() {
  $test_1 = "測試1";
  $test_2 = "測試2";
  $test_2 = "測試3";
  return view('test.index',compact('test_1','test_2' ,'test_3' ));
}

 

數(shù)組的傳遞

 

with

public function index() {
  $data = array( 'test1' => '測試1', 'test2' => '測試2', 'test3' => '測試3' );
  return view('test.index')->with($data);
}
 

view

public function index() {
  $data["test1"] = "測試1";
  $data["test2"] = "測試2";
  $data["test3"] = "測試3";
  return view('test.index',$data);
}
 

compact

//推薦此種方法
public function index() {
  $test_array = ["測試1","測試2", "測試2"];
  return view('test.index',compact('test_array'));
}

以上就是最近整理出來的一些傳值方法,不知道寫法上還有什么更聰明的寫法。

熱門關(guān)鍵詞: Laravel 控制器 Controller 傳值 視圖View
欄目列表
推薦內(nèi)容
熱點內(nèi)容
展開