PHPackages                             neilrussell6/laravel5-json-api - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. neilrussell6/laravel5-json-api

ActiveLibrary[API Development](/categories/api)

neilrussell6/laravel5-json-api
==============================

Laravel 5 JSON API implementation

v0.0.1(9y ago)043PHPPHP &gt;=5.6.4

Since Feb 25Pushed 9y ago1 watchersCompare

[ Source](https://github.com/neilrussell6/laravel5-json-api)[ Packagist](https://packagist.org/packages/neilrussell6/laravel5-json-api)[ RSS](/packages/neilrussell6-laravel5-json-api/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (1)Dependencies (5)Versions (2)Used By (0)

Laravel 5 JSON API
==================

[](#laravel-5-json-api)

Response format:

- [JSON API](http://jsonapi.org/format/)

Usage
-----

[](#usage)

#### Use composer to require packages

[](#use-composer-to-require-packages)

```
composer require neilrussell6\laravel5-json-api dev-master
```

#### Update config/app.php

[](#update-configappphp)

```
    'providers' => [
        ...
        \Neilrussell6\Laravel5JsonApi\Providers\Laravel5JsonApiServiceProvider::class,
        ...
    'aliases' => [
        ...
        'JsonApiUtils' => \Neilrussell6\Laravel5JsonApi\Facades\JsonApiUtils::class
        ...
```

#### Update bootstrap/app.php

[](#update-bootstrapappphp)

```
$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    // App\Exceptions\Handler::class
    \Neilrussell6\Laravel5JsonApi\Exceptions\Handler::class
);
```

#### Update app/Http/Kernel.php

[](#update-apphttpkernelphp)

```
    protected $routeMiddleware = [
        ...
        'jsonapi' => \Neilrussell6\Laravel5JsonApi\Http\Middleware\JsonApi::class,
        ...
```

#### Update routes/api.php

[](#update-routesapiphp)

```
Route::group(['middleware' => ['jsonapi'], 'namespace' => 'Api'], function () {
    ...
```

#### Extend JsonApiController

[](#extend-jsonapicontroller)

eg. if your API will use **app/Http/Controllers/Controller.php** asa base controller, then update as follows:

```
class Controller extends JsonApiController
    ...
    protected $model;
    ...
    public function __construct ($model)
    {
        $this->model = new $model();
        ...
```

Manual testing
--------------

[](#manual-testing)

> NOTE: if you are using MySQL &lt; 5.7.7 then update the character set in **config/database.php** as follows:

```
    ...
    'connections' => [
        ...
        'mysql' => [
            ...
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            ...
```

eg. in laravel/5.4.x:

1. Configure database in **laravel/5.4.x/.env**
2. Run migrations

```
php artisan migrate --path=packages/neilrussell6/laravel5-json-api/src-testing/database/migrations
```

or if using in a project where this package was required via composer:

```
php artisan migrate --path=vendor/neilrussell6/laravel5-json-api/src-testing/database/migrations
```

3. Seed database with sample data

```
art db:seed --class=Neilrussell6\\Laravel5JsonApi\\Seeds\\DatabaseSeeder
```

4. Serve project

```
php artisan serve
```

5. View in [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en)

eg. GET eg. GET eg. GET

Running automated tests
-----------------------

[](#running-automated-tests)

> TODO: create an artisan command to automate all this.

Assuming the following directory structure:

- laravel
    - 5.4.x (contains a clean install of Laravel 5.4.x)
- packages
    - neilrussell6
        - laravel5-json-api

1. Create a symlink from packages to laravel/5.4.x/packages. Repeat for other versions and Lumen.
2. Copy env.testing.example to env.testing
3. Copy everything in src-testing (excluding database directory) into cleaning install (laravel/5.4.x)
4. Update each clean install's composer.json:

```
"autoload-dev": {
    "psr-4": {
        ...
        "Neilrussell6\\Laravel5JsonApi\\": "packages/neilrussell6/laravel5-json-api/src/",
        "Neilrussell6\\Laravel5JsonApi\\Seeds\\": "packages/neilrussell6/laravel5-json-api/src-testing/database/seeds/"
    }
    ...
```

4. Create a testing DB in each clean install (in laravel/5.4.x) and make it executable:

```
touch database/laravel5_json_api_testing.sqlite
sudo chmod -R 777 database/laravel5_json_api_testing.sqlite
```

5. add the following to .env for each clean install (laravel/5.4.x/.env)

```
DB_TESTING_DATABASE=laravel5_json_api_testing.sqlite

```

6. Run migrations (in laravel/5.4.x)

```
php artisan migrate --path=packages/neilrussell6/laravel5-json-api/src-testing/database/migrations --database=sqlite_testing
```

or if using in a project where this package was required via composer:

```
php artisan migrate --path=vendor/neilrussell6/laravel5-json-api/src-testing/database/migrations --database=sqlite_testing
```

7. Update Codeception config before each separate version test

eg. for laravel/5.4.x, update to root property in the following files:

- packages/neilrussell6/laravel5-json-api/tests/api.suite.yml
- packages/neilrussell6/laravel5-json-api/tests/functional.suite.yml

as follows:

```
    root: ../../../laravel/5.4.x/
```

8. Serve project (for Acceptance tests)

eg. in laravel/5.4.x/

```
php artisan serve
```

9. Run tests (in packages/neilrussell6/laravel5-json-api)

```
codecept run
```

Customisation
-------------

[](#customisation)

> You can customize request/response handling by overriding Controller methods

2 helpful tools for customisation are:

1. The package's utility facade **Neilrussell6\\Laravel5JsonApi\\Facades\\JsonApiUtils**
2. The package's Response macros, eg.

```
Response::item
Response::collection
Response::pagination
```

see **src/Providers/Laravel5JsonApiServiceProvider.php** for implementation.

Road Map
--------

[](#road-map)

#### JSON API

[](#json-api)

- Add support to update or create relationships through the relationships object in a request like this: UPDATE /articles/1 { "data": \[ "relationships": { "comments": \[ ... \], "author": { "type": "users", "id": "123" }, } } }
- Add support for paginating related resources
- Add support for include queries
- Add support for sorting
- Add support for filtering

License
-------

[](#license)

[MIT](https://github.com/neilrussell6/markdown-it-code-embed/blob/master/LICENSE)

JWTAuth
=======

[](#jwtauth)

> This package provides support for usage with [JWTAuth](https://github.com/tymondesigns/jwt-auth)

Middleware
----------

[](#middleware)

> This package includes middleware that will transform JWTAuth error responses to conform with JSON API specs.

#### Update app/Http/Kernel.php

[](#update-apphttpkernelphp-1)

```
    protected $routeMiddleware = [
        ...
        'jsonapi.jwt' => \Neilrussell6\Laravel5JsonApi\Http\Middleware\TransformJWTResponse::class,
        ...
```

#### Update routes/api.php

[](#update-routesapiphp-1)

Add 'jsonapi/jwt' middleware to your routes eg.

```
Route::group(['middleware' => ['jsonapi.jwt']], function () {
    ...
```

> NOTE: This middleware will also work with any package that returns single error strings. eg. `[ 'error' => 'some error' ]`

Configuration
-------------

[](#configuration)

#### config/jsonapi.php

[](#configjsonapiphp)

You can configure how error messages are returned by adjusting the JWTAuth mappings in:

- jwt.error\_messages.error\_status\_code (*can be an integer, string or keyed array*)
- jwt.error\_messages.error\_title (*can be a string or keyed array*)
- jwt.error\_messages.error\_detail (*can be a string or keyed array*)

The keys of keyed arrays must correspond with JWTAuth error codes which are:

- token\_not\_provided
- token\_expired
- token\_invalid
- user\_not\_found

ACL
===

[](#acl)

> This package provides support for usage with [Laratrust](https://github.com/santigarcor/laratrust). But the ACL handling is implemented in such a way that it should work with most ACL packages or native Laravel policies/gates, but some configuration may be required.

Configuration
-------------

[](#configuration-1)

#### config/jsonapi.php

[](#configjsonapiphp-1)

You can configure what authorisation checks are called, and how they are called by configuring the following:

- **jwt.acl.check\_access**Whether or not to apply any ACL checks (if false neither ownership nor permission checks will occur).
- **jwt.acl.check\_ownership**Whether or not to check if resource is owned by the user attempting to access/modify it.
- **jwt.acl.check\_permission**Whether or not to check if the user attempting to access/modify the resource has permission to do so. This permission check will correspond to the route name (eg. users.show or tasks.relationships.project.show). So your permissions need to be named according to route names.
- **jwt.acl.check\_ownership\_method**The User model method to call when checking ownership (default is 'owns'). eg. will be called like this: `Auth::user()->owns($resource)`
- **jwt.acl.check\_permission\_method**The User model method to call when checking for permission (default is 'can'). eg. will be called like this: `Auth::user()->can('projects.store', $resource)`

You can also configure how ACL related error messages are returned by adjusting the following:

- acl.error\_messages.error\_status\_code (*can be an integer, string or keyed array*)
- acl.error\_messages.error\_title (*can be a string or keyed array*)
- acl.error\_messages.error\_detail (*can be a string or keyed array*)

The keys of keyed arrays must correspond with the following:

- check\_ownership\_fail
- check\_permission\_fail

This package also comes with a **JsonApiAclSeeder**, which should be used instead of **LaratrustSeeder.php**By default **JsonApiAclSeeder** will look for role, permission structures and maps in **config/laratrust\_seeder.php** but you can define the location of your ACL structure by setting **jsonapi.acl.seeder\_config** in **config/jsonapi.php**, just make sure your ACL's data structure is the same as that of Laratrust.

```
    'acl' => [
        ...
        'seeder_config' => 'laratrust_seeder'
```

When configuration your ACL structure make sure the permissions map follows laravel's route action naming convention eg.

```
    'permissions_map' => [
        'i' => 'index',
        'c' => 'store',
        'r' => 'show',
        'u' => 'update',
        'd' => 'destroy',
    ]
```

Also make sure the module part of your role\_structure is a valid laravel route name, eg.

```
    'role_structure' => [
        'administrator' => [
            'projects' => 'i,c,r,u,d',
            'projects.owner' => 'r',
            'projects.relationship.owner' => 'r',
            'projects.tasks' => 'i',
```

For a list of all the routes in your project use the following command:

```
php artisan route:list
```

#### Role Hierarchy

[](#role-hierarchy)

This package includes optional support for role hierarchies, meaning that if set, a role can override the ownership check for roles with a lower hierarchy than it. eg. if a role called **admin** has a hierarchy of 3 and a role called **subscriber** has a hierarchy of 1, then a user with the **admin** role can perform actions (for which it has permission) on records belonging to users with the **subscriber** role.

To use role hierarchy, update **config/jsonapi.php** as follows:

```
    'acl' => [
        'use_role_hierarchy' => true,
```

Then when creating roles set the `hierarchy` &amp; `is_hierarchical` values.

You can alternatively setup roles using the `JsonApiAclSeeder` seeder, which can be configured as follows:

First define the order of your hierarchy in **config/jsonapi\_acl\_seeder.php**, eg.

```
    'role_hierarchy' => [ // higher overrides lower
        'super_administrator' => 4,
        'administrator' => 3,
        'editor' => 2,
        'moderator' => 2,
        'subscriber' => 1,
    ]
```

Then specify which roles will be hierarchical (by default roles will not be hierarchical)

```
    'hierarchical_roles' => [
        'super_administrator',
        'administrator',
        'editor'
    ],
```

return \[ 'role\_structure' =&gt; \[ 'hierarchical\_roles' =&gt; \[ 'administrator' \],

The above setup will mean that:

- super administrator's will be able to perform any actions they have permissions for, on records owned by users with roles below them in the hierarchy (administrator, editor, moderator, subscriber).
- the same applies for administrator &amp; editor roles.
- however moderators will not be able to perform any actions they have permissions for, on records owned by users with roles below them in the hierarchy, because even though the moderator role is superior to the subscriber role, the moderator role is not hierarchical (as defined in the hierarchical\_roles array in **config/jsonapi.php**.

Then run the `JsonApiAclSeeder`, eg. Add the following to the `run` method of your **database/seeds/DatabaseSeeder.php** file:

```
$this->call(JsonApiAclSeeder::class);
```

This seeder will setup all your roles and permissions data, including role hierarchies according to the configurations detailed above, but will not create any users.

> Remember don't run both the LaratrustSeeder and the JsonApiAclSeeder.

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

3364d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/41617b8eeebb47fc4ff62122df457926504af37c8b88d309e26967ef27130db3?d=identicon)[neilrussell6](/maintainers/neilrussell6)

---

Top Contributors

[![neilrussell6](https://avatars.githubusercontent.com/u/9170147?v=4)](https://github.com/neilrussell6 "neilrussell6 (26 commits)")

---

Tags

laraveljsonapilaravel rest apilaravel-json-apilaravel jsonapi

###  Code Quality

TestsCodeception

### Embed Badge

![Health badge](/badges/neilrussell6-laravel5-json-api/health.svg)

```
[![Health](https://phpackages.com/badges/neilrussell6-laravel5-json-api/health.svg)](https://phpackages.com/packages/neilrussell6-laravel5-json-api)
```

###  Alternatives

[darkaonline/l5-swagger

OpenApi or Swagger integration to Laravel

2.9k34.0M112](/packages/darkaonline-l5-swagger)[openai-php/laravel

OpenAI PHP for Laravel is a supercharged PHP API client that allows you to interact with the Open AI API

3.7k7.6M74](/packages/openai-php-laravel)[knuckleswtf/scribe

Generate API documentation for humans from your Laravel codebase.✍

2.3k12.2M45](/packages/knuckleswtf-scribe)[cloudcreativity/laravel-json-api

JSON API (jsonapi.org) support for Laravel applications.

7881.1M5](/packages/cloudcreativity-laravel-json-api)[laravel-json-api/laravel

JSON:API for Laravel applications.

6371.4M15](/packages/laravel-json-api-laravel)[timacdonald/json-api

A Lightweight JSON:API Resource for Laravel

639892.5k2](/packages/timacdonald-json-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
