Skip to content

kharysharpe/laravel-json-api-resource

Repository files navigation

Overview

Latest Version on Packagist Build Status Quality Score Total Downloads

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.

Installation

You can install the package via composer:

composer require kharysharpe/laravel-json-api-resource

Usage

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);
    }
}

OR

<?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

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email kharysharpe@gmail.com instead of using the issue tracker.

TODO

Credits

License

The MIT License (MIT). Please see License File for more information.

About

Laravel JSON API Resource

Topics

Resources

License

MIT, MIT licenses found

Licenses found

MIT
LICENSE
MIT
LICENSE.md

Stars

Watchers

Forks

Packages

No packages published

Languages