Weave 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

Core Laravel Package

laravel-json-api/core

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require laravel-json-api/core
    

    No publisher or service provider is required—this package is purely contracts and base classes.

  2. First Use Case Use the JsonApiResource trait to create a JSON:API-compliant resource:

    use LaravelJsonApi\Core\Contracts\JsonApiResource;
    use LaravelJsonApi\Core\JsonApiResource as BaseJsonApiResource;
    
    class Post extends BaseJsonApiResource implements JsonApiResource
    {
        public static function type(): string
        {
            return 'posts';
        }
    
        public function attributes(): array
        {
            return [
                'title' => $this->title,
                'body'  => $this->body,
            ];
        }
    }
    
  3. Where to Look First

    • Contracts: LaravelJsonApi\Core\Contracts\JsonApiResource (defines required methods).
    • Base Class: LaravelJsonApi\Core\JsonApiResource (default implementation).
    • Exceptions: LaravelJsonApi\Core\Exceptions\JsonApiException (for custom error handling).

Implementation Patterns

Core Workflows

  1. Resource Definition Extend JsonApiResource and implement type() and attributes():

    class Comment extends JsonApiResource
    {
        public static function type(): string { return 'comments'; }
    
        public function attributes(): array { return ['body' => $this]; }
    }
    
  2. Relationships Use relationships() to define belongs-to/many relationships:

    public function relationships(): array
    {
        return [
            'author' => new ToOneRelationship(
                new AuthorResource(),
                'author_id'
            ),
            'tags' => new ToManyRelationship(
                new TagResource(),
                'tags'
            ),
        ];
    }
    
  3. Pagination & Meta Leverage JsonApiResource::meta() and JsonApiResource::paginate() for compliance:

    public function meta(): array
    {
        return ['published_at' => $this->created_at];
    }
    
  4. Custom Serialization Override toArray() for non-standard JSON:API responses:

    public function toArray($request): array
    {
        return [
            'data' => [
                'type' => 'posts',
                'id'   => $this->id,
                'attributes' => $this->attributes(),
                'links' => ['self' => route('posts.show', $this)],
            ],
        ];
    }
    

Integration Tips

  • API Controllers: Pair with laravel-json-api/v8 for full JSON:API support.
  • Testing: Mock JsonApiResource to test serialization logic:
    $resource = Mockery::mock(Post::class);
    $resource->shouldReceive('attributes')->andReturn(['title' => 'Test']);
    $this->assertEquals(['title' => 'Test'], $resource->attributes());
    
  • Documentation: Use phpdoc to auto-generate OpenAPI specs for resources.

Gotchas and Tips

Pitfalls

  1. Missing type() Forgetting to implement type() throws JsonApiException during serialization. Fix: Always define type() as a static method returning the resource’s plural name (e.g., 'posts').

  2. Circular Relationships Nested relationships without guards cause infinite loops. Fix: Use LaravelJsonApi\Core\Contracts\Relationship and implement lazy-loading:

    public function author()
    {
        return $this->belongsTo(Author::class)->withDefault();
    }
    
  3. Attribute Whitelisting Undeclared attributes in attributes() are silently ignored. Tip: Use protected $hidden or protected $visible to control exposure.

Debugging

  • Enable JSON:API Debugging Add to config/app.php:

    'json-api' => [
        'debug' => env('JSON_API_DEBUG', false),
    ],
    

    Logs malformed responses to storage/logs/json-api.log.

  • Common Exceptions

    • JsonApiException: Invalid resource structure (e.g., missing id or type).
    • RuntimeException: Failed relationship resolution.

Extension Points

  1. Custom Resource Classes Extend JsonApiResource to add shared logic:

    abstract class BaseResource extends JsonApiResource
    {
        public function meta(): array
        {
            return ['updated_at' => $this->updated_at];
        }
    }
    
  2. Middleware for Validation Validate incoming JSON:API requests with:

    use LaravelJsonApi\Core\Validation\JsonApiValidator;
    
    $validator = new JsonApiValidator($request);
    if ($validator->fails()) {
        throw new JsonApiException($validator->errors());
    }
    
  3. Testing Helpers Use JsonApiTestCase (from laravel-json-api/v8) to assert responses:

    $this->assertJsonApiResponse($response)
        ->hasDataOfType('posts')
        ->hasAttributes(['title']);
    
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.
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names