Skip to main content

No Need for response()->json()

Premium
3 min read

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

You also get:

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

Already a member? Login here

Łukasz Gołko avatar

Order::filter($filter) filter() method is not defined. i have not found it. is it method provided by laravel?

Modestas avatar

This method comes from a model scope:

public function scopeFilter(Builder $query, QueryFilter $filters)
{
return $filters->apply($query);
}

Within Laravel, this will get transformed to Order::filter() sine it drops the scope and just uses the Filter part

Łukasz Gołko avatar

where i can read about it in documentation becouse i have only found local scope but there is #[Scope] not scopeFunction.

Modestas avatar

It's the same thing!

The scopeFunction was there before we even had the attributes (the #[Scope] thing). So they work identically, and you can find them in Laravel 11 documentation: https://laravel.com/docs/11.x/eloquent#local-scopes