Skip to main content

Route Model Binding

Premium
4 min read

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 of our courses? (30 h 09 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.