framework icon indicating copy to clipboard operation
framework copied to clipboard

[12.x] JSON:API Resource

Open crynobone opened this issue 1 month ago • 2 comments

This PR allows you to output your API Resources using JSON:API specification instead of normal JSON via JsonResource. You need to update your existing resource class to extends JsonApiResource instead of JsonResource:

-use Illuminate\Http\Resources\Json\JsonResource;
+use Illuminate\Http\Resources\JsonApi\JsonApiResource;

-class UserResource extends JsonResource
+class UserResource extends JsonApiResource
{

Relationships

The response from JsonApiResource will not lazy load relationships, you need to manually include it using include query string such as /users/11?include=posts,teams using the following code:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/users/{user}', function (Request $request, User $user) {
    return $user->toResource();
});

Server Implementation

You can configure jsonapi object https://jsonapi.org/format/#document-jsonapi-object on each response using JsonApiResource::configure() method.

use Illuminate\Http\Resources\JsonApi\JsonApiResource;

JsonApiResource::configure(version: '2.0.0');

crynobone avatar Oct 29 '25 12:10 crynobone