Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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