百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
L

laravel5-jsonapi

> 后端框架
开源

Laravel 5 JSON API Transformer 包

310 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

Laravel 5 JSON API Transformer 包

Laravel 5 JSON API Server Package

Compatible with Laravel 5.0, 5.1 & 5.2

  • Package provides a full implementation of the JSON API specification, and is featured on the official site!
  • A JSON API Transformer that will allow you to convert any mapped object into a valid JSON API resource.
  • Controller boilerplate to write a fully compiliant JSON API Server using your exisiting Eloquent Models.
  • Works for Laravel 5 and Lumen frameworks.

  • Installation
  • Configuration (Laravel 5 & Lumen)
    • Configuration for Laravel 5
      • Step 1: Add the Service Provider
      • Step 2: Defining routes
      • Step 3: Definition
      • Step 4: Usage
    • Configuration for Lumen
      • Step 1: Add the Service Provider
      • Step 2: Defining routes
      • Step 3: Definition
      • Step 4: Usage
  • JsonApiController
  • Examples: Consuming the API
    • GET
    • POST
    • PUT
    • PATCH
    • DELETE
  • GET Query Params: include, fields, sort and page
  • POST/PUT/PATCH with Relationships
  • Custom Response Headers
  • Common Errors and Solutions

Installation

Use Composer to install the package:

composer require nilportugues/laravel5-json-api

Now run the following artisan command:

php artisan vendor:publish

Configuration (Laravel 5 & Lumen)

For the sake of having a real life example, this configuration will guide you on how to set up 7 end-points for two resources, Employees and Orders.

Both Employees and Orders resources will be Eloquent models, being related one with the other.

Furthermore, Employeeswill be using an Eloquent feature, appended fields to demonstrate how it is possible to make the most of Eloquent and this package all together.

Configuration for Laravel 5

Step 1: Add the Service Provider

Open up config/app.php and add the following line under providers array:

php
'providers' => [
    //...
    NilPortugues\Laravel5\JsonApi\Laravel5JsonApiServiceProvider::class,
],

Step 2: Defining routes

We will be planning the resources ahead its implementation. All routes require to have a name.

This is how our app/Http/routes.php will look:

php
 'Api'], function() {
    Route::resource('employees', 'EmployeesController');    
    Route::get(
        'employees/{employee_id}/orders', [
        'as' => 'employees.orders',
        'uses' => 'EmployeesController@getOrdersByEmployee'
    ]);
});
//...

Step 3: Definition

First, let's define the Models for Employees and Orders using Eloquent.

Employees (Eloquent Model)

php
hasMany(Orders::class, 'employee_id')->limit(10);
    }

    /**
     * @return string
     */
    public function getFullNameAttribute()
    {
        return $this->first_name.' '.$this->last_name;
    }
}

Employees SQL

…

Orders (Eloquent Model)

php
belongsTo(Employees::class, 'employee_id');
    }
}

Orders SQL

…

Follow up, we'll be creating Transformers. One Transformer is required for each class and it must implement the \NilPortugues\Api\Mappings\JsonApiMapping interface.

We will be placing these files at app/Model/Api:

EmployeesTransformer

…

Same goes for Orders, these files will also be placed at app/Model/Api:

OrdersTransformer

php
 ['name' => 'orders.show', 'as_id' => 'id'],
            'employee' => ['name' => 'employees.show', 'as_id' => 'employee_id'],
        ];
    }
    /**
     * {@inheritDoc}
     */
    public function getRelationships()
    {
        return [];
    }
    
    /**
     * List the fields that are mandatory in a persitence action (POST/PUT). 
     * If empty array is returned, all fields are mandatory.
     */
    public function getRequiredProperties()
    {
        return [];
    }    
} 

Step 4: Usage

Create file config/jsonapi.php. This file should return an array returning all the class mappings.

php
register(\NilPortugues\Laravel5\JsonApi\Laravel5JsonApiServiceProvider::class);
$app->configure('jsonapi');

Also, enable Facades by uncommenting:

php
$app->withFacades();

Step 2: Defining routes

We will be planning the resources ahead its implementation. All routes require to have a name.

This is how our app/Http/routes.php will look:

…

Step 3: Definition

Same as Laravel 5.

Step 4: Usage

Same as Laravel 5.

JsonApiController

Whether it's Laravel 5 or Lumen, usage is exactly the same.

Let's create a new controller that extends the JsonApiController provided by this package, as follows:

Lumen users must extends from LumenJsonApiController not JsonApiController.

…

And you're ready to go. Yes, it is THAT simple!

Examples: Consuming the API

GET

This is the output for EmployeesController@getAction being consumed from command-line method issuing: curl -X GET "http://localhost:9000/employees/1".

Output:

HTTP/1.1 200 OK
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/vnd.api+json
…

POST

POST requires all member attributes to be accepted, even those hidden by the mapper.

For instance, attachments member was hidden, but it is required, so it needs to be passed in with a valid value. On the other hand, full_name member value must not be passed in as an attribute or resource creation will fail.

Passing and id is optional and will be used instead of a server-side generated value if provided.

Sending the following data to the server using POSTto the following URI http://localhost:9000/employees:

…

Will produce:

HTTP/1.1 201 Created
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/vnd.api+json
Location: http://localhost:9000/employees/10

Notice how 201 HTTP Status Code is returned and Location header too. Also attachments is not there anymore, and full_name was displayed.

…

PUT

PUT requires all member attributes to be accepted, just like POST.

For the sake of this example, we'll just send in a new job_title value, and keep everything else exactly the same.

It's important to notice this time we are required to pass in the id, even if it has been passed in by the URI, and of course the id values must match. Otherwise it will fail.

Sending the following data to the server using PUTto the following URI http://localhost:9000/employees/10:

…

Will produce:

HTTP/1.1 200 OK
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/vnd.api+json
…

PATCH

PATCH allows partial updates, unlike PUT.

We are required to pass in the id member, even if it has been passed in by the URI, and of course the id values must match. Otherwise it will fail.

For instance, sending the following data to the server using the following URI http://localhost:9000/employees/10:

json
{
  "data": {
    "type": "employee",
    "id": 10,
    "attributes": {
      "email_address": "[email protected]"
    }
  }
}

Will produce:

HTTP/1.1 200 OK
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/vnd.api+json
…

DELETE

DELETE is the easiest method to use, as it does not require body. Just issue a DELETE to http://localhost:9000/employees/10/ and Employee with id 10 will be gone.

It will produce the following output:

HTTP/1.1 204 No Content
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/vnd.api+json

And notice how response will be empty:

GET Query Params: include, fields, sort and page

According to the standard, for GET method, it is possible to:

  • Show only those fields requested using fieldsquery parameter.
    • &fields[resource]=field1,field2

For instance, passing /employees/10?fields[employee]=company,first_name will produce the following output:

…
  • Show only those include resources by passing in the relationship between them separated by dot, or just pass in list of resources separated by comma.
    • &include=resource1
    • &include=resource1.resource2,resource2.resource3

For instance, /employees?include=order will only load order type data inside include member, but /employees?include=order.employee will only load those orders related to the employee type.

  • Sort results using sort and passing in the member names of the main resource defined in data[type] member. If it starts with a - order is DESCENDING, otherwise it's ASCENDING.

    • &sort=field1,-field2
    • &sort=-field1,field2

For instance: /employees?sort=surname,-first_name

  • Pagination is also defined to allow doing page pagination, cursor pagination or offset pagination.
    • &page[number]
    • &page[limit]
    • &page[cursor]
    • &page[offset]
    • &page[size]

For instance: /employees?page[number]=1&page[size]=10

POST/PUT/PATCH with Relationships

The JSON API allows resource creation and modification and passing in relationships that will create or alter existing resources too.

Let's say we want to create a new Employee and pass in its first Ordertoo.

This could be done issuing 2 POST to the end-points (one for Employee, one for Order) or pass in the first Order as a relationship with our Employee, for instance:

…

Due to the existance of this use case, we'll have to ajust our Controller implementation overwriting some methods provided by the JsonApiController: createResourceCallable, updateResourceCallable and patchResourceCallable.

Here's how it would be done for createResourceCallable.

…

It is important, in order to use Transactions, do define in Eloquent models the $fillable values.

Here's how Employees and Orders look like with $fillable defined.

Employees (Eloquent Model) with $fillable

php
hasMany(Orders::class, 'employee_id')->limit(10);
    }

    /**
     * @return string
     */
    public function getFullNameAttribute()
    {
        return $this->first_name.' '.$this->last_name;
    }
}

Orders (Eloquent Model) with $fillable

php
belongsTo(Employees::class, 'employee_id');
    }
}

Custom Response Headers

Adding custom response headers can be done for multiple reasons: versioning, setting expire headers, caching, setting private or public the served content...

In order to do this, it's as simple as overwriting the JsonApiController addHeaders method. For instance, let's use the EmployeeController as an example:

php
headers->set('X-API-Version', '1.0');
        $response->setPublic();
        $response->setMaxAge(60);
        $response->setSharedMaxAge(60);

        return $response;
    }
}    

Now all supported actions will include the added custom headers.

Common Errors and Solutions

"Undefined index: @type"

This usually happens because you did not write the namespace of your Mapping in config/jsonapi.php. Double check, if missing, add it and refresh the resource. It should be gone!


Contribute

Contributions to the package are always welcome!

  • Report any bugs or issues you find on the [issue tracker](https://github.com/nilportugues/laravel5-jsonapi-transformer/issues/ne

Issues· 41 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPapijsonjson-apijsonapi

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架