Skip to content

Instantly share code, notes, and snippets.

@nicoaudy
Created April 27, 2019 08:00
Show Gist options
  • Save nicoaudy/9d8fb4a4d4bce742f5d918bbd199f2f7 to your computer and use it in GitHub Desktop.
Save nicoaudy/9d8fb4a4d4bce742f5d918bbd199f2f7 to your computer and use it in GitHub Desktop.
trait for api
<?php
namespace App\Http\Traits;
use Illuminate\Http\Response;
trait ApiController {
/**
* @var int
*/
protected $statusCode = Response::HTTP_OK;
/**
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* @param $statusCode
*
* @return $this
*/
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
return $this;
}
/**
* @param string $message
*
* @return mixed
*/
public function respondNotFound($message = 'Not Found')
{
return $this->setStatusCode(Response::HTTP_NOT_FOUND)->respondWithError($message);
}
/**
* @param string $message
*
* @return mixed
*/
public function respondBadRequest($message = 'Bad Request')
{
return $this->setStatusCode(Response::HTTP_BAD_REQUEST)->respondWithError($message);
}
/**
* @param string $message
*
* @return mixed
*/
public function respondServerError($message = 'Server Error')
{
return $this->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR)->respondWithError($message);
}
/**
* @param string $message
*
* @return mixed
*/
public function respondConflict($message = 'Conflict')
{
return $this->setStatusCode(Response::HTTP_CONFLICT)->respondWithError($message);
}
/**
* @param string $message
*
* @return mixed
*/
public function respondUnprocessable($message = 'Unprocessable Entity')
{
return $this->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY)->respondWithError($message);
}
/**
* @param string $message
*
* @return mixed
*/
public function respondUnauthorized($message = 'Unauthorized')
{
return $this->setStatusCode(Response::HTTP_UNAUTHORIZED)->respondWithError($message);
}
/**
* @param string $message
*
* @return mixed
*/
public function respondForbidden($message = 'Forbidden')
{
return $this->setStatusCode(Response::HTTP_FORBIDDEN)->respondWithError($message);
}
/**
* @param array $data
*
* @return mixed
*/
public function respondCreated($data = [])
{
return $this->setStatusCode(Response::HTTP_CREATED)->respond($data);
}
/**
* @param $data
* @param array $headers
*
* @return mixed
*/
public function respond($data, $headers = [])
{
return response()->json($data, $this->getStatusCode(), $headers);
}
/**
* @param $message
*
* @return mixed
*/
public function respondWithError($message)
{
return $this->respond([
'error' => [
'data' => $message,
'status_code' => $this->getStatusCode()
]
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment