laravel5.5を使ってAPIサーバを構築していきます。その2。
前記事
https://nitd.co.jp/blog/laravel5-5api/
CRUDメソッドを整備
まだindexで全userを返しているだけなのでその他のメソッドを作成していきます。
新規登録(store)
public function store(Request $request) { $item = User::create($request->all()); $item->save(); return response($item); }
まずユーザの新規登録メソッドです。storeという関数が担当します。
バリデーションやエラーハンドリングは割愛。
これで/api/users にPOSTでuser新規登録できるように。
$ curl -X POST -d "name=testuser001&email=hogehoge@fugafuga.com&password=secret" http://127.0.0.1:8000/api/users {"name":"testuser001","email":"hogehoge@fugafuga.com","updated_at":"2018-06-11 09:07:14","created_at":"2018-06-11 09:07:14","id":51}
APIへの簡易テストはコマンドラインからcurlでやると便利。
1件取得(show)
public function show($id) { $item = User::find($id); return response($item); }
$ curl -X GET http://127.0.0.1:8000/api/users/1 {"id":1,"name":"Arvel Zulauf MD","email":"abshire.savion@example.net","created_at":"2018-06-10 08:31:10","updated_at":"2018-06-10 08:31:10"}
更新(update)
public function update(Request $request, $id) { $item = User::find($id); $item->fill($request->all())->save(); return response($item); }
$ curl -X PUT -d "name=testuserAAAA&email=hogehogeAAA@fugafuga.com" http://127.0.0.1:8000/api/users/1 {"id":1,"name":"testuserAAAA","email":"hogehogeAAA@fugafuga.com","created_at":"2018-06-10 08:31:10","updated_at":"2018-06-11 09:25:58"}
削除(destroy)
public function destroy($id) { $item = User::find($id); $suc = $item->delete(); return response(['suc' => $suc]); }
$ curl -X DELETE http://127.0.0.1:8000/api/users/1 {"suc":true}
createとeditは不要なので削除
php artisan make:controller –resource で作成すると自動でついてくるメソッドですが、入力画面htmlを出力するためのものなので不要となります。
public function create() { // } public function edit($id) { // }
削除しておきましょう。
エラーレスポンスをJSONに修正
デフォルトだとエラーのレスポンスがHTMLになっているので、app/Exceptions/Handler.phpのrenderメソッドを以下のように修正。
public function render($request, Exception $exception) { if ($request->is('api/*') || $request->ajax()) { $status = 400; if ($this->isHttpException($exception)) { $status = $exception->getStatusCode(); } $res = [ 'status' => $status, 'errors' => $exception->getMessage() ]; return response($res, $status); } else { return parent::render($request, $exception); } }