Courses

Laravel API Code Review and Refactor

Handling AuthorizationException Globally

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

Link to the repository

[Only for premium members]

We continue shortening the OrderController, and now I want to remove the try-catch with AuthorizationException.

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

public function show(Order $order)
{
try {
$this->isAble('view', $order); // policy
 
// ...
 
return new OrderResource($order);
} catch (AuthorizationException $eAuthorizationException) {
return $this->responseNotAuthorized();
}
}

There is no need to do this manually in every Controller method. That Exception can also be handled automatically by Laravel.


Controller Cleanup

So, we will remove this try-catch in THREE methods of this Controller.

BEFORE:

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

class OrderController extends ApiController
{
// ...
 
public function show(Order $order)
{
try {
$this->isAble('view', $order); // policy
 
if ($this->include('user')) {
$order->load('user');
}
 
$order->load('products');
 
return new OrderResource($order);
} catch (AuthorizationException $eAuthorizationException) {
return $this->responseNotAuthorized();
}
}
 
public function update(UpdateOrderRequest $request, Order $order)
{
try {
$this->isAble('update', $order); // policy
$this->orderService->updateOrderHandleProducts($request, $order);
 
return response()->json(new OrderResource($order), Response::HTTP_OK);
} catch (AuthorizationException $eAuthorizationException) {
return $this->responseNotAuthorized();
} 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 destroy(Order $order)
{
try {
$this->isAble('delete', $order); // policy
$this->orderService->deleteOrderHandleProducts($order);
 
return $this->responseSuccess('Order deleted successfully');
} catch (AuthorizationException $eAuthorizationException) {
return $this->responseNotAuthorized();
}
}
}

AFTER:

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