资源路由只是系统自动帮你注册了一些资源的restful路由规则
Route::resource('goods', 'GoodsController');
则会创建如下路由
动作 | URI | 行为 | 路由名称 |
---|---|---|---|
GET | /goods | index | goods.index |
GET | /goods/create | create | goods.create |
POST | /goods | store | goods.store |
GET | /goods/{good} | show | goods.show |
GET | /goods/{good}/edit | edit | goods.edit |
PUT/PATCH | /goods/{good} | update | goods.update |
DELETE | /goods/{good} | destroy | goods.destroy |
需要注意的是,以 PUT/PATCH/DELETE 请求时,需要在标签内加一行
{{ method_field(‘PUT/PATCH/DELETE’) }}
因为html表格不支持PUT/PATCH/DELETE 的请求方法
如果不想用{good}作为参数,可以加参数
parameters
Route::resource('goods', 'GoodsController', ['parameters' => ['goods' => 'id']]);
具体代码
//商品
Route::resource('goods', 'GoodsController', ['parameters' => ['goods' => 'id']]);
// Route::get('/goods', 'GoodsController@index')->name('goods.index');
// Route::get('/goods/{good}', 'GoodsController@show')->name('goods.show');
// Route::get('/goods/create', 'GoodsController@create')->name('goods.create');
// Route::post('/goods', 'GoodsController@store')->name('goods.store');
// Route::get('/goods/{good}/edit', 'GoodsController@edit')->name('goods.edit');
// Route::patch('/goods/{good}', 'GoodsController@update')->name('goods.update');
// Route::delete('/goods/{good}', 'GoodsController@destroy')->name('goods.destroy');
如果在namespace App\Http\Requests目录下想获取id可以用
$id = $this->route('id');
具体代码
<?php
namespace App\Http\Requests;
use Illuminate\Validation\Rule;
class GoodsRequest extends FormRequest
{
public function rules()
{
$id = $this->route('id');
//自己的代码
//.......
}
public function messages()
{
return [
//自己的代码
//.......
];
}
}
再控制其中直接用
public function show(GoodsRequest $request)
{
$goods = Goods::find($request->id);
if($goods) {
return $goods;
} else {
return '商品不存在';
}
}