Courses

Laravel API Code Review and Refactor

OrderController with no try-catch: Final Version

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

Link to the repository

[Only for premium members]

In this lesson, we will finalize our big goal of shortening the OrderController and removing the other try-catch methods.

app/Http/Controllers/Api/V1/OrderController.php

public function store(StoreOrderRequest $request)
{
Gate::authorize('create', Order::class);
 
try {
$order = $this->orderService->createOrderHandleProducts($request);
 
return response()->json(new OrderResource($order), Response::HTTP_CREATED);
} catch (QueryException $eQueryException) {
DB::rollback(); // Rollback transaction on database error
 
return $this->responseDbError();
} catch (Throwable $eTh) {
DB::rollback(); // Rollback transaction on any other error
 
return $this->responseUnexpectedError();
}
}
 
public function update(UpdateOrderRequest $request, Order $order)
{
Gate::authorize('update', $order);
 
try {
$this->orderService->updateOrderHandleProducts($request, $order);
 
return response()->json(new OrderResource($order), Response::HTTP_OK);
} catch (QueryException $eQueryException) {
DB::rollback(); // Rollback transaction on database error
 
return $this->responseDbError();
} catch (Throwable $eTh) {
DB::rollback(); // Rollback transaction on any other error
 
return $this->responseUnexpectedError();
}
}

Those try-catch blocks "clutter" the Controller, trying to catch Exceptions, which we can move to the bootstrap/app.php, like we did in the previous lessons with 404 and 403 status code Exceptions.

As a result, I hope to also entirely eliminate two Trait methods: responseDbError() and responseUnexpectedError(). Or maybe even remove that Trait altogether. We'll see.


Exceptions from Controller to bootstrap/app.php File

First, let's remove those from the Controller.

The methods are simplified to just THIS:

app/Http/Controllers/Api/V1/OrderController.php

public function store(StoreOrderRequest $request)
{
Gate::authorize('create', Order::class);
 
$order = $this->orderService->createOrderHandleProducts($request);
 
return response()->json(new OrderResource($order), Response::HTTP_CREATED);
}
 
public function update(UpdateOrderRequest $request, Order $order)
{
Gate::authorize('update', $order);
 
$this->orderService->updateOrderHandleProducts($request, $order);
 
return response()->json(new OrderResource($order), Response::HTTP_OK);
}

Then, we handle those Exceptions in the same...

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

You also get:

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