0712-2888027 189-8648-0214
微信公众号

孝感风信网络科技有限公司微信公众号

当前位置: 主页 > 技术支持 > PHP > Laravel Controller控制器传值到View视图的几种方法

Laravel Controller控制器传值到View视图的几种方法

时间:2019-01-08来源:风信网 点击:

总体内容分为传值类型和方法,大概总体感觉如下。

传值类型:一个值,多个值,数组。
方法: with,view,compact
默认视图 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' ));
}

数组的传递

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'));
}
栏目列表
推荐内容
热点内容
展开