本篇文章主要描述资源路由在后台管理中如何应用。
目录
简介
资源路由,采用固定的常用方法来实现简化 URL 的功能。
Route::resource('test', 'Test');
快速生成命令
$ php think make:controller Test
Controller:app\controller\Test created successfully.
生成多个方法,包含了显示、增删改查等多个操作方法。
注册资源路由
在路由定义文件下创建一条资源路由,资源名称可自定义;
Route::resource('test', 'Test');
这里的 test 表示资源规则名,Test 表示路由的控制器和访问路径。
资源路由注册成功后,会自动提供以下方法,无须手动注册;
GET 访问模式下:index(test),create(test/create),read(test/:id),edit(test/:id/edit)
POST 访问模式下:save(test);
PUT 方式模式下:update(test/:id);
DELETE 方式模式下:delete(test/:id);
http://www.xxx.com/Test/ (index)
http://www.xxx.com/Test/5 (read)
http://www.xxx.com/Test/5/edit (edit)
对于 POST,一般是表单的 POST 新增提交
<form action="Test/{$id}" method="post"
accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="__token__" value="{{:token()}}">
<div class="form-group">
<label class="col-sm-2 control-label">用户名:</label>
<div class="input-group col-sm-2">
<input type="text" class="form-control" name="name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">密码:</label>
<div class="input-group col-sm-2">
<input type="password" class="form-control" name="password">
</div>
</div>
<input type="submit" value=”提交” />
</form>
而 PUT 和 DELETE 可用 AJAX 访问
$.ajax({
type : "DELETE",
data : {
id : 6,
__token__: "{{:token()}}",
},
url : "http://wwww.xxx.com/Test/6",
success : function (res) {
console.log(res);
}
});
伪装请求方法
PUT/DELETE也可以使用伪装请求方法,在表单中提交。
<input type="hidden" name="_method" value="PUT" >
<input type="hidden" name="_method" value="DELETE" >
改变参数名称
默认的参数采用 id 名称,如果你想别的,比如:test_id,则:
->vars(['test'=>'test_id']);
//相应的 注册路由应为test/:test delete($test_id)
限定资源方法
可以通过 only()方法限定系统提供的资源方法,比如:
->only(['index','save','create']);
排除资源方法
可以通过 except()方法排除系统提供的资源方法,比如:
->except(['read','delete']);
更改默认方法
使用 rest()方法,更改系统给予的默认方法:1.请求方式2.地址3.操作
// 方法名称create改为add
Route::rest('create', ['GET', '/add', 'add']);
Route::resource('test', 'Test');
设置之后,URL访问变为:
http://www.xxx.com/test/create
变为
http://www.xxx.com/test/add
批量
Route::rest([
'create' => ['get', '/add', 'add'],
'delete' => ['DELETE', '/:id', 'destory'],
]);