dees040 / laravel-api-responses
Helper methods for Laravel API Responses
Installs: 20 440
Dependents: 3
Suggesters: 0
Security: 0
Stars: 68
Watchers: 5
Forks: 5
Open Issues: 0
Requires
- illuminate/http: ~5.0|~6.0|~7.0|~8.0|~9.0|~10.0|~11.0
- illuminate/routing: ~5.0|~6.0|~7.0|~8.0|~9.0|~10.0|~11.0
Requires (Dev)
- phpunit/phpunit: ^9.0
README
A very small package which helps you to easily returning readable API responses.
Installation
Install the package via Composer.
composer require dees040/laravel-api-responses
You're ready to go!
Usage
Just use one of the helper functions and you're good to go.
<?php namespace App\Http\Controllers; use App\User; use App\Http\Controllers\Controller; class UsersController extends Controller { /** * Show the given user. * * @param \App\User $user * @return \Illuminate\Http\Response */ public function show(User $user) { if (! $user->isAdmin()) { return forbidden(); } return ok($user); } }
Methods
All methods accept a $data
parameter. This can be any data which can be used in a JSON response, such as strings, integers, arrays, models, etc..
Custom response (code)
If you'd wish to send a status code which is not in the list you could use the json_response($data = null, $status = 200)
helper function. Here you can find a cheat sheet for HTTP status codes or use my personal favorite http.cat 😉.
If you want to send error response you can use the error_json_response($message = '', $errors = [], $status = 400)
. This method will send an json response like this:
error_json_response('User not found.', [ 'id' => 'The ID does not exists.' ]);
Output:
{ "message": "User not found.", "errors": { "id": "The ID does not exists." } }