Avoiding Magic HTTP Codes in Laravel

Here’s a quick tip if you need to use HTTP status codes in your project. Don’t use magic numbers like 200 and 404: instead, use defined constants which are easier to read and less likely to result in mistakes.

To illustrate this, instead of writing code like this:

1
2
3
return response()->json([
'message' => $err->getMessage(),
], 400);

do something like this:

1
2
3
4
5
6
7
8
use Symfony\Component\HttpFoundation\Response;

...

return response()->json([
'message' => $err->getMessage(),
], Response::HTTP_BAD_REQUEST);

You have very likely got the Symfony components installed and within the Response class, they have already been defined for you:


Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com