Link to the repository
[Only for premium members]
[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.
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: