Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Json Api Laravel Package

timacdonald/json-api

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require timacdonald/json-api
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="TimMacDonald\JsonApi\JsonApiServiceProvider"
    
  2. Create a Resource Generate a resource class for your model (e.g., User):

    php artisan make:json-api User
    

    This creates app/Http/Resources/UserResource.php.

  3. Basic Usage In your controller, return the resource:

    use App\Http\Resources\UserResource;
    
    public function show(User $user)
    {
        return new UserResource($user);
    }
    

First Use Case: Simple API Endpoint

// routes/api.php
Route::get('/users/{user}', [UserController::class, 'show']);

// app/Http/Controllers/UserController.php
public function show(User $user)
{
    return new UserResource($user);
}

This automatically adheres to JSON:API standards, returning:

{
  "data": {
    "type": "users",
    "id": "1",
    "attributes": {
      "name": "John Doe",
      "email": "john@example.com"
    }
  }
}

Implementation Patterns

Core Workflow: CRUD with JSON:API

  1. Index (List)

    public function index()
    {
        return UserResource::collection(User::all());
    }
    

    Returns paginated data with links and meta by default.

  2. Store (Create)

    public function store(Request $request)
    {
        $user = User::create($request->validated());
        return new UserResource($user, 201);
    }
    
  3. Update/Delete

    public function update(Request $request, User $user)
    {
        $user->update($request->validated());
        return new UserResource($user);
    }
    
    public function destroy(User $user)
    {
        $user->delete();
        return response()->noContent();
    }
    

Sparse Fieldsets

Request specific fields via fields query parameter:

// GET /users?fields[users]=name,email
return new UserResource($user);

Resource must define fields:

public static $fields = ['name', 'email', 'created_at'];

Relationships

Define relationships in the resource:

public function toRelationships()
{
    return [
        'posts' => PostResource::collection($this->posts),
        'author' => new UserResource($this->author)
    ];
}

Eager-load relationships in the controller:

public function show(User $user)
{
    return new UserResource($user->load('posts', 'author'));
}

Compound Documents

Include related resources in the response:

// GET /users/1?include=posts,author
return new UserResource($user->load('posts', 'author'));

Customizing Responses

Override default behavior:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'custom_key' => 'custom_value',
    ];
}

Gotchas and Tips

Pitfalls

  1. Eager Loading

    • Forgetting to eager-load relationships causes N+1 queries.
    • Use load() in the controller or with() in the resource:
      public static $with = ['posts']; // Auto-loads in every request
      
  2. Fieldset Mismatches

    • If $fields is not defined, all attributes are returned.
    • Undefined fields in $fields are silently ignored (no error).
  3. Relationship Resource Guessing

    • The package auto-guesses relationship resource classes (e.g., PostPostResource).
    • Override with resourceClass():
      public function posts()
      {
          return $this->belongsToMany(Post::class)->resourceClass(PostResource::class);
      }
      
  4. Meta/Data Conflicts

    • Avoid naming attributes meta or data to prevent conflicts with JSON:API top-level keys.

Debugging

  • Check the Raw Output Use dd($resource->resolve()) to inspect the resolved resource before serialization.

  • Enable JSON:API Debugging Set JSON_API_DEBUG in .env to log fieldset/relationship issues:

    JSON_API_DEBUG=true
    

Tips

  1. Reuse Resources Extend base resources for shared logic:

    class BaseResource extends JsonApiResource
    {
        public function toMeta()
        {
            return ['version' => '1.0'];
        }
    }
    
  2. Custom Error Handling Override failedValidation() for API-specific errors:

    public function failedValidation(Validator $validator)
    {
        return response()->json([
            'errors' => $validator->errors(),
        ], 422);
    }
    
  3. Performance

    • Use select() to limit loaded columns:
      return UserResource::collection(User::select(['id', 'name'])->get());
      
    • Cache resources for read-heavy APIs:
      return Cache::remember("user-{$user->id}", now()->addHours(1), function() use ($user) {
          return new UserResource($user);
      });
      
  4. Testing Use JsonApiTestCase for assertions:

    $response = $this->getJson('/users/1?fields[users]=name');
    $response->assertJsonStructure([
        'data' => [
            'type', 'id', 'attributes' => ['name']
        ]
    ]);
    
  5. Extending the Package

    • Add custom directives via JsonApiServiceProvider:
      JsonApi::directive('custom', function ($resource) {
          $resource->addAttribute('custom_field', 'value');
      });
      
    • Use JsonApi::extend() to modify the resource class dynamically.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope