laravel api return response code example

Example 1: laravel return response json

return response()->json([
    'name' => 'Abigail',
    'state' => 'CA',
]);

Example 2: laravel api response trait

trait RespondsWithHttpStatus
{
    protected function success($message, $data = [], $status = 200)
    {
        return response([
            'success' => true,
            'data' => $data,
            'message' => $message,
        ], $status);
    }

    protected function failure($message, $status = 422)
    {
        return response([
            'success' => false,
            'message' => $message,
        ], $status);
    }
}

Example 3: laravel check if api request

if (Request::wantsJson()) {
    // return JSON-formatted response
} else {
    // return HTML response
}