Courses

Laravel API Code Review and Refactor

Route Model Binding

You're reading a FREE PREVIEW of a PREMIUM course.

Link to the repository

[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.


Controller to Route Model Binding

This part is simple:

  • Type-hint the Model
  • Remove the findOrFail()
  • Remove one of the catch parts

app/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');
}
}

Catch the 404 Exception Globally

Next, we need to catch that ModelNotFoundException, showing exactly the same error message as in the...

The full lesson is only for Premium Members.
Want to access all 15 lessons of this course? (56 min read)

You also get:

  • 76 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord