behamin / bresources
Behamin basic and standard api response format for laravel
Installs: 2 460
Dependents: 1
Suggesters: 0
Security: 0
Stars: 6
Watchers: 2
Forks: 2
Open Issues: 0
Requires
- php: ^7.4 || ^8.0
- ext-json: *
- laravel/framework: ^8.67 || ^9.52 || ^10.13
Requires (Dev)
- orchestra/testbench: ^v6.27.1 || ^7.24 || ^8.5
README
Behamin Resources
Behamin standard formats for api responses.
Installation
composer require behamin/bresources
Output Format
Resources:
{ "data": { "id": 1, "email": "test@test.com" }, "message": "message", "error": { "message": "or error message", "errors": null } }
ResourceCollection:
{ "data": { "items": [], "count": 0, "sum": null }, "message": null, "error": { "message": null, "errors": null } }
On validation error for requests (with 422 status code):
{ "data": null, "message": null, "error": { "message": "first error message in message bag", "errors": { "password": [ "password field is required." ] } } }
Usage
Create resources and requests with artisan commands and pass data, message, error_message or count to resources like following examples:
public function index(EmailFilter $filters) { list($emails, $count) = Email::filter($filters); $emails = $emails->get(); return EmailResource::collection(['data' => $emails, 'count' => $count]); }
public function show(Email $email) { return new EmailResource(['data' => $email, 'message'=> 'email info.']); }
You can specify output fields from transformDataItem() method of resource classes.
<?php namespace App\Http\Resources; use Behamin\BResources\Resources\BasicResource; class EmailResource extends BasicResource { protected function transformDataItem($item) { return [ 'id' => $item->id, 'email' => $item->email, 'status' => $item->status ]; } }
Also, you can use apiResponse() helper function to directly send response
class PhoneController { public function show(Phone $phone) { return apiResponse()->data($phone)->message('phone info.')->status(200)->get(); } public function index() { $phones = Phone::all(); return apiResponse()->collection($phones, $phones->count())->message('phone info.')->status(200)->get(); } public function update(Request $request, Phone $phone) { $isUpdated = $phone->update($request->all()); if (!$isUpdated) { return apiResponse()->errors('phone is not updated'); } return apiResponse()->data($phone)->message('phone is updated')->get(); } public function delete(Phone $phone) { $phone->delete(); return apiResponse()->message('phone info.')->next('https://debut.test')->status(200)->get(); } }
In above example message and status are optional, and their default value respectively are null
and 200
.
Resource
php artisan make:bresource ResourceClassName
Request
php artisan make:brequest RequestClassName