A shop needs new inventory. Add product.create so staff can insert a row without opening a SQL console.
What you will learn
- Implement
createActionwithtable('products')->save() - Confirm with a follow-up
product.list
Before you start
Add createAction
protected function createAction(Arrayable $data): ApiResponse
{
$product = table('products')->save([
'name' => $data->get('name'),
'price' => $data->get('price'),
'stock' => $data->getInt('stock') ?? 0,
]);
return response(0, 'Product created', ['id' => $product->id]);
}save() returns the saved row as an object. Read its id property for the response.
Try it
curl -s -X POST http://127.0.0.1:8000/api/v1/ \
-H "Content-Type: application/json" \
-d '{"service":"product","action":"create","name":"Tote Bag","price":18.00,"stock":40}'Then product.list again — the tote should appear. Step 8 adds validation so empty names are rejected cleanly.
Common mistakes
- Passing
titleinstead ofname— match your column names - Forgetting to cast/check stock — use
getIntwhen you expect an integer