DEV Community

Jakz ⚡
Jakz ⚡

Posted on

Return Status Code with Laravel Resource

Laravel Resource is one of the best features in Laravel. It makes it easy to modify the output of the result. If you're using an API, you need to have a status code to let the front-end know what the status of the request is.

Example of Status Code
202 - Created
401 - Unauthorized
404 - Not Found

You may find a list of HTTP status code over here.

For example, you have a User Model, and the controller wants to return user information of specific id. You want to let the front-end know that you found the data based on the status code.

Api.php

Route::get('user/{user}', 'UserController@show');

UserController.php

public function show(User $user) {
    return (new UserResource($user))
        ->response()
        ->setStatusCode(202);
}

How about if there is no ID in the database?

It could be like this. We should check it first whether the ID is available in our database and if not, it should return a status code of not found. If yes, we may proceed with the previous system.

UserController.php

public function show(User $user) {

    // If user not found
    if(!$user){
    return response(array(
        'message' => 'Not Found',
     ), 410);
    } else {
        // If user is found
        return (new UserResource($user))
            ->response()
            ->setStatusCode(202);
    }
}

It is writing with if else block is troublesome during debugging. It's a best practice to check for the negative result first and then returns the correct output at last. If the if else get deeper it will get worse for the developer.

Refactor

public function show(User $user) {

    // If user not found
    if(!$user){
    return response(array(
        'message' => 'Not Found',
     ), 410);
    }

    // If user is found
    return (new UserResource($user))
        ->response()
        ->setStatusCode(202);
}

Hope it may help you understand how to send the status code through laravel resource or without it.

Original submitted from my blog

Top comments (0)