This is potentially a drop in replacement for Laravel API Resource that produces JSON API response as per specification. (https://jsonapi.org/).
* Needs refactoring and tests, pull requests welcomed.
You can install the package via composer:
composer require kharysharpe/laravel-json-api-resource
Pre-made example https://github.com/kharysharpe/laravel-json-api-resource-example
From scratch
laravel new json-server
cd json-server
composer require kharysharpe/laravel-json-api-resource
routes/api.php
<?php
Route::get('/users', 'UserController@index');
Route::get('/users/{id}', 'UserController@show');
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Kharysharpe\LaravelJsonApiResource\Http\Resource\JsonApi\Resource;
use Kharysharpe\LaravelJsonApiResource\Http\Resource\JsonApi\ResourceCollection;
class UserController extends Controller
{
public function index()
{
$user = User::all();
return new ResourceCollection($user);
}
public function show($id)
{
$user = User::find($id);
return new Resource($user);
}
}
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Resource\UserCollection;
use App\Http\Resource\UserResource;
class UserController extends Controller
{
public function index()
{
$user = User::all();
return new UserCollection($user);
}
public function show($id)
{
$user = User::find($id);
return new UserResource($user);
}
}
app/Http/Resource/UserResource.php
<?php
namespace App\Http\Resource;
use Kharysharpe\LaravelJsonApiResource\Http\Resource\JsonApi\Resource;
class UserResource extends Resource
{
//
}
app/Http/Resource/UserCollection.php
<?php
namespace App\Http\Resource;
use Kharysharpe\LaravelJsonApiResource\Http\Resource\JsonApi\ResourceCollection;
class UserCollection extends ResourceCollection
{
}
Prepare the database (Don't forget to add data to the user table)
php artisan migrate
Start your laravel application
php artisan serve
Visit
composer test
Please see CHANGELOG for more information what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email kharysharpe@gmail.com instead of using the issue tracker.
- Add credits and/or references
- Look at using https://github.com/spatie/laravel-json-api-paginate to fix pagination
The MIT License (MIT). Please see License File for more information.