到專案目錄底下輸入 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測試