Courses

Laravel API Code Review and Refactor

No Need for response()->json()

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

Link to the repository

[Only for premium members]

Another thing I noticed is how OrderController is returning response()->json() everywhere:

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

public function show($order_id)
{
// ...
 
return response()->json(new OrderResource($order), Response::HTTP_OK);
}

The thing is that if Laravel detects the API call, it automatically returns JSON, so you don't need to specify this manually.

The Response::HTTP_OK (200 status code) is also returned automatically by Laravel.

So, in this case, the "Laravel way" code would be just this:

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

public function show($order_id)
{
// ...
 
return new OrderResource($order);
}

The only reason why it may be beneficial to specify response()->json() and the status code is if 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