2 years ago Sun, Jan 2, 2022

Better Http Status Codes In Laravel

'Magic numbers' like 200 or 401 can cause a lot of confusion for colleagues or your future self. It's not always immediately obvious what these numbers represent.

A magic number is a number in the code that has no context or meaning.

Luckily, when it comes to HTTP Status Codes, we can make use of a complete set of constants that will make the meaning of your code self evident.

return Response::HTTP_OK;

For example, Response::HTTP_OK will return 200, Response::HTTP_UNAUTHORIZED will return 401 and my personal favourite Response::HTTP_I_AM_A_TEAPOT will return 418.

This is possible because the Illuminate\Http\Response class extends the Symfony\Component\HttpFoundation\Response class.

Finally, we also have access to an array of all status codes via Response::$statusTexts. This is handy if you want to list, validate or otherwise iterate over all status codes.

Thank you for reading this article.

If you've made it this far, you might like to connect with me on 𝕏 where I post similar content and interact with like-minded people. If this article was helpful to you I'd really appreciate it if you would consider buying me a coffee.