Skip to content

Instantly share code, notes, and snippets.

@niksumeiko
Last active December 22, 2015 06:49
Show Gist options
  • Save niksumeiko/6434188 to your computer and use it in GitHub Desktop.
Save niksumeiko/6434188 to your computer and use it in GitHub Desktop.
Demonstration of PHP Laravel framework Response class methods that sets custom HTTP status codes in your Controller response. Especially handy when wish to manage your REST API error responses.
<?php
class Users_Controller extends Base_Controller {
public function action_index() {
$id = Input::get('id');
if ($id) {
$user = DB::table('users')->where('id', $id)->first();
if (count($user)) {
// If user (queried by id) has been found in the database,
// returning JSON with it's data, with 200 HTTP request status.
return Response::json($user, 200);
}
}
// Otherwise, if user id is not provided or user is not found in the
// database, returning error message with 404 HTTP request status.
return Response::make('User not found', 404);
}
jQuery.ajax({
dataType: 'json',
url: '/users',
data: {
id: 12345678
},
// If HTTP response status code is 4XX (error)
// Check status codes for more info: http://httpstatus.es
error: function(xhr) {
/** @type {number} HTTP response status code */
xhr.status;
/** @type {string} HTTP response text */
xhr.responseText;
},
// If HTTP response status code is 2XX (success)
success: function(data, status, xhr) {
/** @type {Object} HTTP response body */
data;
/** @type {number} HTTP response status code */
xhr.status;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment