Link to the repository
[Only for premium members]
[Only for premium members]
The next piece of code I didn't like is the OrderController
methods NOT using Route Model Binding:
app/Http/Controllers/Api/V1/OrderController.php
public function show($order_id){ try { $order = Order::findOrFail($order_id); // ... } catch (ModelNotFoundException $eModelNotFound) { return $this->responseNotFound('Order not found'); }} public function update(UpdateOrderRequest $request, $order_id) try { $order = Order::findOrFail($order_id); // ... } catch (ModelNotFoundException $eModelNotFound) { return $this->responseNotFound('Order not found'); }} public function destroy($order_id) try { $order = Order::findOrFail($order_id); // ... } catch (ModelNotFoundException $eModelNotFound) { return $this->responseNotFound('Order not found'); }}
We shouldn't need to call the ModelNotFoundException
manually, Laravel can do that internally.
That said, we need to preserve the same response with the Order not found
message, so this refactoring is not as easy as you may expect.
This part is simple:
findOrFail()
catch
partsapp/Http/Controllers/Api/V1/OrderController.php
public function show($order_id) public function show(Order $order) { try { $order = Order::findOrFail($order_id); // ... } catch (ModelNotFoundException $eModelNotFound) { return $this->responseNotFound('Order not found'); }} public function update(UpdateOrderRequest $request, $order_id) public function update(UpdateOrderRequest $request, Order $order) try { $order = Order::findOrFail($order_id); // ... } catch (ModelNotFoundException $eModelNotFound) { return $this->responseNotFound('Order not found'); }} public function destroy($order_id) public function destroy(Order $order) try { $order = Order::findOrFail($order_id); // ... } catch (ModelNotFoundException $eModelNotFound) { return $this->responseNotFound('Order not found'); }}
Next, we need to catch that ModelNotFoundException
, showing exactly the same error message as in the...