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? (30 h 09 min)

You also get:

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

Already a member? Login here

Comments & Discussion

�G
Łukasz Gołko ✓ Link copied!

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

M
Modestas ✓ Link copied!

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

�G
Łukasz Gołko ✓ Link copied!

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

M
Modestas ✓ Link copied!

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

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.