I have created a basic Laravel REST API that will service some JavaScript applications that are using axios to make requests.
My application is using a Base Controller to ensure all responses are sent in the same format:
class BaseController extends Controller{ /** * success response method. * * @param $result * @param $message * * @return JsonResponse */ public function sendResponse($result, $message) { $response = ['success' => true,'data' => $result,'message' => $message, ]; return response()->json($response, 200); } /** * return error response. * * @param $error * @param array $errorMessages * @param int $code * * @return JsonResponse */ public function sendError($error, $errorMessages = [], $code = 200) { $response = ['success' => false,'message' => $error, ]; if (!empty($errorMessages)) { $response['data'] = $errorMessages; } return response()->json($response, $code); }}
When I retrieve the response from the API URL and log it to the console, I get the following output:
Currently, my response object contains its own data object, which then contains another data object. As a result, to access the data I have to use response.data.data.
I am wondering if this is actually the correct way to do this. As the naming convention of response.data.data doesn't seem to be a very clean way to do this. I have seen a couple of guides online where it has been done this way, but I am wondering if there are any typically followed conventions that I am missing. Perhaps this is correct but I just wanted some insight from more experienced programmers.