| Package Data | |
|---|---|
| Maintainer Username: | shalvah |
| Maintainer Contact: | shalvah.adebayo@gmail.com (Shalvah Adebayo) |
| Package Create Date: | 2017-06-21 |
| Package Last Update: | 2023-04-07 |
| Home Page: | http://shalvah.me/laravel-jsend/ |
| Language: | PHP |
| License: | MIT |
| Last Refreshed: | 2025-11-04 03:02:41 |
| Package Statistics | |
|---|---|
| Total Downloads: | 107,631 |
| Monthly Downloads: | 1,652 |
| Daily Downloads: | 21 |
| Total Stars: | 62 |
| Total Watchers: | 3 |
| Total Forks: | 16 |
| Total Open Issues: | 0 |
Simple helpers to generate JSend-compliant responses for your Laravel app
The JSend specification lays down some rules for how JSON responses from web servers should be formatted. JSend is especially suited for REST-style applications and APIs.
In your controller:
public function create(Request $request)
{
$userData = $request->input('data');
if (empty($userData['email']))
return jsend_fail(['email' => 'Email is required']);
try {
$user = User::create($userData):
return jsend_success($user);
} catch (Exception $e) {
return jsend_error('Unable to create user: '.$e->getMessage());
}
}
jsend_successThe jsend_success function creates a JSend success response instance.
return jsend_success([
"id" => 2,
"title" => "New life",
"body" => "Trust me, this is great!"
]);
Generates a response:
{
"status": "success",
"data": {
"id": 2,
"title": "New life",
"body": "Trust me, this is great!"
}
}
You may pass an Eloquent model instead of an array as the "data" object:
$post = Post::find($id);
return jsend_success($post);
jsend_failThe jsend_fail function creates a JSend fail response instance.
return jsend_fail([
"title" => "title is required",
"body" => "body must be 50 - 10000 words"
]);
Generates a response:
{
"status": "fail",
"data": {
"title": "title is required",
"body": "body must be 50 - 10000 words"
}
}
jsend_errorThe jsend_error function creates a JSend error response instance.
return jsend_error("Unable to connect to database");
Generates a response:
{
"status": "error",
"message":"Unable to connect to database"
}
You may also pass optional code and data objects.
return jsend_error("Unable to connect to database", 'E0001', ['type' => 'database error']);
Generates a response:
{
"status": "error",
"message":"Unable to connect to database",
"code": "E001",
"data": {
"type": "database error"
}
}
Note: for each helper, the HTTP status codes are set automatically (to 200, 400, and 500 for
success,fail, anderrorrespectively), and the headerContent-type: application/jsonis set. If you wish, you may specify a HTTP status code and additional headers as the last two parameters.
return jsend_success($post, 201, ["X-My-Header" => "header value"]);
return jsend_fail(["location_id" => "Location not found"], 404);
return jsend_error("Unable to connect to database", 'E0001', [], 503, ["X-My-Header" => "header value"]);
composer require shalvah/laravel-jsend
MIT