This post is from the professional Laravel developer community, original link: learnku.com/laravel/t/9…

Returning a status code in an API is important because response handlers work on top of the API’s response status code.

One important aspect of writing apis is better handling of response status codes. Previously, I used to use the unusual Integer type as an HTTP status code. Take a look at this example:

<? php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Post; Class PostsController extends Controller{ publicfunction store() {$post = new Post(request()->only('title'.'description'));
    request()->user()->posts()->save($post);
    return response()->json(['post'= >$post], 201); }}Copy the code

During API calls, if data has been created, the HTTP 201 status code will be responded to, but most developers are not aware of the 201 status code and are more familiar with the 200 success status code. Use the Symfony Response class to solve this problem. It contains all the HTTP status codes and uses simpler names. The above code can be changed to the following code:

<? php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Post; use Symfony\Component\HttpFoundation\Response; Class PostsController extends Controller{ publicfunction store() {$post = new Post(request()->only('title'.'description'));
    request()->user()->posts()->save($post);
    return response()->json(['post'= >$post], Response::HTTP_CREATED); }}Copy the code

This class contains all defined HTTP status codes. Let’s take a look at some of them first:

While I don’t think it’s a bad habit to write numeric HTTP status codes directly, it’s better to use some self-explanatory names when using HTTP status codes. Happy coding everyone!