Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Handling 404 API Error

Premium
2 min read

Now that we have our CRUD operations, we should check that basic functionality works as expected. In this case, we want to ensure we correctly handle 404 errors. Let's look at the default way:

We can do better than this.


Correctly Handling 404 Error

We tried to load a category with the ID of 123 with our first test but got a long message. This was because we have APP_DEBUG=true in our .env file. We can change this to APP_DEBUG=false to see what we would get in a production environment:

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

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

Already a member? Login here

Comments & Discussion

AU
Artem Ushakov ✓ Link copied!

I guess here it is much better to return response()->json(['message' => '...'], 404) Since by default, it will return 200 code, that typically means "Ok", that might be misleading. And I know from experience that detecting errors by error text is pain in the arse, however when you receive 404, then there is no any misunderstanding here.

M
Modestas ✓ Link copied!

You are right! I completely missed this case, where we override the status code (thought it was automatic in this case)

M
Modestas ✓ Link copied!

Okay, I have taken another look at it seems - that I haven't missed it! It's at the end (scroll needed) :)

AU
Artem Ushakov ✓ Link copied!

Oh, my bad, FF didn't show me the scrolling at first. Sorry :)

OB
Oscar Boot ✓ Link copied!

Is there a specifc reason that you use " renderable()" instead of "render()" which is in the Laravel 12 documentation and also works?

M
Modestas ✓ Link copied!

It might be that it's almost the same thing now. But in this case, renderable was just to trigger this before it's even passed full workflow.

Honestly, not sure at this point what has changed between renderable() and render()