-
-
Save tadejgasparovic/ec913c496b40db366b3434c7b122f4ad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use Illuminate\Http\Request; | |
use Illuminate\Http\Response; | |
use Illuminate\Pagination\LengthAwarePaginator; | |
class ApiController extends Controller | |
{ | |
protected function respondSuccess($data = [], $message = 'Success'){ | |
return $this->respond($data, $message); | |
} | |
protected function respondNotFound($message = 'Not Found'){ | |
return $this->respond([], $message, Response::HTTP_NOT_FOUND, 'error'); | |
} | |
protected function respondUnauthorized($message = 'Unauthorized'){ | |
return $this->respond([], $message, Response::HTTP_UNAUTHORIZED, 'error'); | |
} | |
protected function respondValidationError($errors = [], $message = 'Validation Error'){ | |
return $this->respond($errors, $message, Response::HTTP_UNPROCESSABLE_ENTITY, 'error'); | |
} | |
protected function respondInternalError($message = 'Woops, something went wrong!'){ | |
return $this->respond([], $message, Response::HTTP_INTERNAL_SERVER_ERROR, 'error'); | |
} | |
protected function respondCreated($data = [], $message = 'Created'){ | |
return $this->respond($data, $message, Response::HTTP_CREATED); | |
} | |
protected function respondWithPagination(LengthAwarePaginator $paginate, $data = [], $message = 'Success'){ | |
$data = array_merge($data, [ | |
'paginator' => [ | |
'total_count' => $paginate->total(), | |
'total_pages' => ceil($paginate->total() / $paginate->perPage()), | |
'current_page' => $paginate->currentPage(), | |
'limit' => $paginate->perPage(), | |
'has_more' => $paginate->hasMorePages(), | |
] | |
]); | |
return $this->respond($data, $message); | |
} | |
protected function respond($data = [], $message = null, $status_code = Response::HTTP_OK, $status = 'success'){ | |
$response = [ | |
'status' => $status, | |
'status_code' => $status_code, | |
'message' => $message, | |
'data' => $data | |
]; | |
return response()->json($response); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment