【轉】Laravel 控制器 Controller 傳值到 視圖 View 的幾種方法總結


單個值的傳遞

 

with

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

view

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

compact

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

 

多個值的傳遞

 

with

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

view

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

compact

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

 

數組的傳遞

 

with

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

view

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

compact

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

from :https://www.cnblogs.com/cici1989/p/10723131.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM