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

Laravel Laravel Package

api-platform/laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require api-platform/laravel
    

    Run migrations if included in the package:

    php artisan migrate
    
  2. Basic Configuration:

    • Publish the config file:
      php artisan vendor:publish --provider="ApiPlatform\Laravel\ApiPlatformServiceProvider" --tag="api-platform"
      
    • Configure config/api-platform.php to match your API needs (e.g., enable/disable features like filters, pagination, or serialization groups).
  3. First Use Case:

    • Annotate a model with #[ApiResource]:
      use ApiPlatform\Metadata\ApiResource;
      
      #[ApiResource]
      class Post
      {
          // Model logic
      }
      
    • Test the API endpoint at /api/posts (or your configured route prefix).

Implementation Patterns

Common Workflows

  1. Resource Configuration:

    • Use attributes to define API behavior:
      #[ApiResource(
          operations: [
              new Get(),
              new Post(),
              new GetCollection(),
              new Patch(),
              new Delete(),
          ],
          normalizationContext: ['groups' => ['post:read']],
          denormalizationContext: ['groups' => ['post:write']],
      )]
      class Post {}
      
    • Override operations dynamically via ApiResource methods (e.g., getOperations()).
  2. State Providers:

    • Handle custom logic for POST, PUT, or PATCH:
      use ApiPlatform\Metadata\Operation;
      use ApiPlatform\State\ProcessorInterface;
      
      #[ApiResource(processor: MyCustomProcessor::class)]
      class Post {}
      
      class MyCustomProcessor implements ProcessorInterface
      {
          public function process($data, Operation $operation, array $uriVariables = [], array $context = [])
          {
              // Custom logic (e.g., validation, business rules)
              return $data;
          }
      }
      
  3. Filters and Pagination:

    • Enable built-in filters (e.g., search, date, boolean) in config/api-platform.php:
      'collection' => [
          'pagination' => ['enabled' => true, 'items_per_page' => 30],
          'filters' => ['search', 'date', 'boolean'],
      ],
      
    • Create custom filters by implementing ApiFilterInterface.
  4. Serialization Groups:

    • Use groups to control which fields are exposed:
      #[Groups(['post:read'])]
      #[ApiProperty(identifier: true)]
      public ?int $id = null;
      
      #[Groups(['post:write'])]
      public ?string $title = null;
      
  5. Authentication/Authorization:

    • Integrate with Laravel’s auth (e.g., Sanctum, Passport):
      #[ApiResource(
          security: "is_granted('ROLE_ADMIN')",
          securityMessage: 'Access denied.'
      )]
      class AdminPost {}
      
    • Use #[Security] attribute for granular control.
  6. Event Handling:

    • Listen to API events (e.g., pre.extract, post.persist):
      use ApiPlatform\Symfony\EventListener\EventPriorities;
      
      public function onPostPersist(PostPersistEvent $event)
      {
          $post = $event->getData();
          // Custom logic (e.g., logging, notifications)
      }
      
    • Register listeners in EventSubscriber or directly in ApiPlatformServiceProvider.

Integration Tips

  • Laravel Mix/Vite: Ensure API routes are proxied if using frontend frameworks (e.g., Vue/React).
  • Testing: Use ApiPlatform\Bundle\Test\ApiTestCase for API tests:
    public function testGetPosts(): void
    {
        $response = $this->get('/api/posts');
        $this->assertResponseIsSuccessful();
    }
    
  • Documentation: Auto-generate OpenAPI/Swagger docs via #[OpenApi] attributes or api-platform/openapi package.

Gotchas and Tips

Pitfalls

  1. Caching:

    • API Platform caches responses by default. Disable or configure in config/api-platform.php:
      'http_cache' => [
          'enabled' => false,
          // or customize TTL/headers
      ],
      
    • Clear cache after schema changes:
      php artisan api-platform:cache:clear
      
  2. Route Conflicts:

    • Ensure #[ApiResource] routes don’t clash with Laravel’s web routes. Use route() middleware to prioritize:
      Route::group(['middleware' => 'api'], function () {
          // API Platform routes
      });
      
  3. Serialization Issues:

    • Circular references (e.g., PostUser) may cause errors. Use #[ApiProperty(serialize: false)] or implement ApiResource\Metadata\PostSerialize:
      #[ApiResource]
      class Post
      {
          #[ApiProperty(serialize: false)]
          public User $author;
      }
      
  4. Pagination:

    • Default pagination may not work with custom queries. Use #[ApiFilter] or override getCollection():
      #[ApiResource(getCollection: MyCustomCollection::class)]
      class Post {}
      
  5. Validation:

    • Laravel’s validation rules (e.g., #[Assert\NotBlank]) work, but API Platform may override them. Use denormalizationContext to enforce:
      #[ApiResource(
          denormalizationContext: ['validation_groups' => ['default', 'post']]
      )]
      
  6. Database Drivers:

    • API Platform assumes Eloquent. For custom ORMs (e.g., Doctrine), configure ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtension.

Debugging Tips

  1. Enable API Debug Toolbar:

    // config/api-platform.php
    'debug' => env('APP_DEBUG', false),
    
    • View request/response details, filters, and serialization groups.
  2. Log Serialization:

    • Enable serialization logging:
      #[ApiResource(
          serializationContext: ['groups' => ['post:read'], 'enable_max_depth' => true]
      )]
      
  3. Common Errors:

    • "No route found": Verify #[ApiResource] is annotated and routes are generated (php artisan route:list).
    • 500 Errors: Check Laravel logs (storage/logs/laravel.log) for validation or ORM issues.
    • CORS Issues: Configure CORS middleware (e.g., fruitcake/laravel-cors) if needed.

Extension Points

  1. Custom Formats:

    • Add support for formats (e.g., JSON-LD, XML) via ApiPlatform\Metadata\Format:
      #[ApiResource(formats: ['jsonld', 'html'])]
      
  2. GraphQL:

    • Use api-platform/graphql to expose GraphQL endpoints alongside REST.
  3. Webhooks:

    • Trigger webhooks on API events (e.g., post.persist) using ApiPlatform\Symfony\EventListener\EventPriorities.
  4. Admin Panel:

    • Integrate with api-platform/admin for a built-in admin interface.
  5. Testing:

    • Extend ApiTestCase for reusable test logic:
      class CustomApiTestCase extends ApiTestCase
      {
          protected function createTestPost(): Post
          {
              return Post::factory()->create();
          }
      }
      
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views