Response Macro for JSend

Submitted by icylace - 3 years ago

I made a response macro that makes use of the JSend specification (http://labs.omniti.com/labs/jsend). UPDATE (2014-09-15): Added the setting of the content type.

//
// Defines a server response that follows the JSend specification
// (http://labs.omniti.com/labs/jsend).
//
Response::macro('jsend', function ($status, $data = null, $message = null, $code = null) {
  switch ($status) {
    case 'success':
    case 'fail':
      $content = ['status' => $status, 'data' => $data];
      break;
    default:
      $content = ['status' => 'error', 'message' => $message];
      if ($data) {
        $content['data'] = $data;
      }
      if ($code) {
        $content['code'] = $code;
      }
  }
  $response = Response::make($content);
  $response->header('Content-Type', 'application/json');
  return $response;
});

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks