【转】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

posted on 2020-03-08 13:57  神奇的旋风  阅读(730)  评论(0编辑  收藏  举报

导航