到专案目录底下输入
php artisan make:controller ProductController
创建一个controller 有预设的CRUD函数
接着修改里面的程序码
首先先引入
use Illuminate\Support\Facades\DB;
然後修改里面的程序码,用一个getData函数来回传一些假资料
然後修改CRUD函数
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() // 使用get方法
{
$data = $this->getData(); // 取得资料
return response($data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request) // 新增,使用post方法
{
$data = $this->getdata();
$newdata = $request->all(); // 取得使用者传递资料
$data->push(collect($newdata)); // 新增
return response($data);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id) // 更新,使用put方法
{
$data = $this->getdata();
$form = $request->all();
$selectdata = $data->where('id', $id)->first(); // 找到要更新的那笔资料
$selectdata = $selectdata->merge(collect($form)); // 修改合并
return response($selectdata);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id) // 删除,使用delete方法
{
$data = $this->getdata();
$data = $data->filter(function($product) use ($id){
return $product['id'] != $id;
});
return response($data->values());
}
public function getdata()
{
return collect([
collect([ "id" => 0,
"name" => "cellphone",
"price" => 1000]),
collect([ "id" => 1,
"title" => "computer",
"price" => 2000])
]);
}
app\Providers\RouteServiceProvider.php
新增路由namespaceprotected $namespace = 'App\\Http\\Controllers';
web.php
Route::resource('/product', 'productController');
web.php
表单会经过CSRF TOKEN的验证app\Http\Middleware\VerifyCsrfToken.php
protected $except = [
'*'
];
明天使用POSTMAN来打API测试
>>: 【狂贺】JACKSOFT持续通过110年经济部工业局审查,成为台湾第一家GRC (治理,风险管理与法规遵循)应用软件产品技术服务能量登录公司!
从开始写文至今已经介绍过 HDMI、色差、SCART 和 S-Video 等 4 种端子了、但在序文...
人生真的很奇妙 可能在某个时间轴曾经跟某个人的时间轴交错 但当下是不认识的 然後在几年过後又再次交...
如同「决定系数篇」所介绍,R^2的数字越趋近於1,模型能够解释的能力越强,那麽我们就是追寻更好的R^...
这三小系列 本来我报名了软件开发组,但是我某天忘记发文了~ 所以再开了新系列拿个参加奖 Who Am...
我们终於要开始实作我们的单元测试了, 首先我们先建立一个自己的测试案例 php artisan ma...