Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:如果前面掌握了, 这里应该是水到渠成的事
$result['res']=$data;
, return view('home/goods',$result);
,传输到goods.blade.php页面中的数据是echo $res
在当前文件夹下打开终端,输入以下命令
新建indexCon控制器
php artisan make:controller home/goodsCon
新建goodsCon控制器
php artisan make:controller home/indexCon
新建控制器后,目录结构如下
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//get方法的第一个参数'/'代表网站的入口地址,第二个参数访问的是app/http/controllers/home下的indexCon控制器的index方法
Route::get('/', 'home\indexCon@index');
//get方法的第一个参数'/home/article'访问地址为backstage.com/goods,第二个参数访问的是app/http/controllers/home下的goodsCon控制器的index方法
Route::get('/goods','home\goodsCon@index');
//添加商品
Route::get('/goods/add','home\goodsCon@addGoods');
//删除商品
Route::get('/goods/del','home\goodsCon@delGoods');
//更新商品
Route::get('/goods/update','home\goodsCon@updateGoods');
<?php
namespace App\Http\Controllers\home;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
class goodsCon extends Controller
{
//
public function index()
{
return $this->showGoods();
}
//显示商品
public function showGoods()
{
$res = DB::select('select * from tb_goods');
$data = [];
foreach($res as $key=>$val):
$data[] = (array)$val;
endforeach;
//注意goods.blade.php文件接收的是$result数组中的键名为res的这个变量的值
$result['res']=$data;
return view('home/goods',$result);
}
//添加商品
public function addGoods()
{
$date = date('Y-m-d');
$res = DB::insert("insert into `tb_goods` (`name`,`price`,`unit`,`sdate`) values ('黄桃','10','斤','$date') ");
echo $res;
}
//删除商品
public function delGoods()
{
$res = DB::delete('delete from tb_goods where id>22');
echo $res;
}
//更新商品
public function updateGoods()
{
$res = DB::update('update tb_goods set name="西瓜" where id="22"');
echo $res;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>前台商品展示页</title>
<link rel="stylesheet" href="layui/css/layui.css">
<script src="layui/layui.js"></script>
</head>
<body>
<h2>商品展示页</h2>
<table class="layui-table">
<thead>
<tr>
<td>商品编号</td>
<td>商品名称</td>
<td>商品单价</td>
<td>商品单位</td>
<td>发布日期</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<?php
/* $res 这个变量的值是来自showCon控制器中 */
foreach($res as $goods):
?>
<tr>
<td><?php echo $goods['id'];?></td>
<td><?php echo $goods['name'];?></td>
<td><?php echo $goods['price'];?></td>
<td><?php echo $goods['unit'];?></td>
<td><?php echo $goods['sdate'];?></td>
<td><button class="layui-btn">修改</button><button class="layui-btn">删除</button></td>
</tr>
<?php
endforeach;
?>
</tbody>
</table>
</body>
</html>