-
php教程之使用Laravel集成JWT认证开发RestfulApi(8)
这个也非常容易理解。我们只需要根据 ID 找到该产品。如果产品不存在,则返回 400 故障响应。否则,将返回产品数组。
接下来是 store 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public function store(Request $request) { $ this ->validate($request, [ 'name' => 'required' , 'price' => 'required|integer' , 'quantity' => 'required|integer' ]); $product = new Product(); $product->name = $request->name; $product->price = $request->price; $product->quantity = $request->quantity; if ($ this ->user->products()->save($product)) return response()->json([ 'success' => true , 'product' => $product ]); else return response()->json([ 'success' => false , 'message' => 'Sorry, product could not be added' ], 500); } |
在 store 方法中,验证请求中是否包含名称,价格和数量。然后,使用请求中的数据去创建一个新的产品模型。如果,产品成功的写入数据库,会返回成功响应,否则返回自定义的 500 失败响应。
实现 update 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public function update(Request $request, $id) { $product = $ this ->user->products()->find($id); if (!$product) { return response()->json([ 'success' => false , 'message' => 'Sorry, product with id ' . $id . ' cannot be found' ], 400); } $updated = $product->fill($request->all()) ->save(); if ($updated) { return response()->json([ 'success' => true ]); } else { return response()->json([ 'success' => false , 'message' => 'Sorry, product could not be updated' ], 500); } } |