Sunday, January 2, 2022 4:10 PM

Better Http Status Codes In Laravel

This Laravel quick tip will show you how to make your code more readable and expressive by replacing http status code magic numbers with calls to static constants.

Tips
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.
I hope you learned something useful.
If you've made it this far, you might like to follow me on Twitter where I post similar content and connect with like-minded people.
Follow me on Twitter
Swift
List All Glyph Names For A Font In Swift
List All Glyph Names For A Font In Swift

This code snippet will show you how to print a list of all the glphys in a particular font using Swift.

Read this article
Laravel
Different Ways To Pass Data To A Laravel View
Different Ways To Pass Data To A Laravel View

Laravel views allow you to pass data to a view in a number of different ways. In this article, I'll go over four methods and describe the pros and cons for each one.

Read this article
Privacy Policy
Copyright © 2022 Carl Cassar. All Rights Reserved.