How to use HTTP Status Codes properly in Laravel

Muhammad Nauman
1 min readMar 22, 2018

--

Response codes in APIs are crucial because the response handlers works on the basis of the status codes returned from them.

One of the core aspects of writing APIs is handling the response status codes better. Few days back, I used to set status code as integer value which can be referred as magic numbers. Let’s take this example:

Status codes as magic numbers

HTTP status code 201 should be returned if the data is created during the API call but many developers don’t know or familiar with success codes other than 200. This problem can be solved with using Symfony Response class. It has all the status codes defined with easy to understand variable names. Above code can be changed to this:

This class has all the list of status codes defined. Have a look at some of them:

I don’t find writing numeric values of status codes directly as a bad habit but using it with better and self explanatory names is better. Happy coding!

--

--