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

Filament Api Service Laravel Package

rupadana/filament-api-service

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require rupadana/filament-api-service
    

    Publish the config file:

    php artisan vendor:publish --provider="Rupadana\FilamentApiService\FilamentApiServiceServiceProvider" --tag="config"
    
  2. Enable for a Resource Add the ApiService trait to your Filament resource:

    use Rupadana\FilamentApiService\Traits\ApiService;
    
    class PostResource extends Resource
    {
        use ApiService;
    
        // ...
    }
    
  3. First API Endpoint After enabling, API endpoints are automatically generated for CRUD operations:

    • GET /api/resources/posts (List)
    • POST /api/resources/posts (Create)
    • GET /api/resources/posts/{id} (Retrieve)
    • PUT /api/resources/posts/{id} (Update)
    • DELETE /api/resources/posts/{id} (Delete)

    Test with:

    curl -X GET http://your-app.test/api/resources/posts -H "Authorization: Bearer YOUR_TOKEN"
    

Key Configuration

  • Authentication: Configure in config/filament-api-service.php under auth.
    'auth' => [
        'driver' => 'sanctum', // or 'passport', 'jwt'
        'guard' => 'api',
    ],
    
  • Base Path: Customize the API prefix:
    'base_path' => 'api/v1',
    

Implementation Patterns

Common Workflows

1. Resource-Level Customization

Override default behavior for specific resources:

class PostResource extends Resource
{
    use ApiService;

    public static function getApiService(): array
    {
        return [
            'enabled' => true,
            'public' => false, // Disable public access
            'middleware' => ['throttle:60,1'], // Add middleware
            'transformer' => PostTransformer::class, // Custom transformer
        ];
    }
}

2. Global API Configuration

Configure defaults in config/filament-api-service.php:

'defaults' => [
    'enabled' => true,
    'public' => false,
    'transformer' => \App\Transformers\DefaultTransformer::class,
    'filters' => true, // Enable query filters
    'sorting' => true, // Enable sorting
],

3. Query Builder Integration

Leverage Spatie’s laravel-query-builder for dynamic queries:

use Spatie\QueryBuilder\QueryBuilder;

class PostResource extends Resource
{
    use ApiService;

    public static function getApiServiceQueryBuilder(): QueryBuilder
    {
        return QueryBuilder::for(Post::class)
            ->allowedFilters('title', 'published_at')
            ->allowedSorts('title', 'created_at');
    }
}

4. Transformer Usage

Create a transformer to customize API responses:

namespace App\Transformers;

use Rupadana\FilamentApiService\Transformers\Transformer;

class PostTransformer extends Transformer
{
    public function transform($resource)
    {
        return [
            'id' => $resource->id,
            'title' => $resource->title,
            'slug' => $resource->slug,
            'created_at' => $resource->created_at->toDateTimeString(),
        ];
    }
}

5. Multi-Tenancy Support

Enable tenant-aware APIs:

'tenancy' => [
    'enabled' => true,
    'model' => \Stancl\Tenancy\Database\Models\Tenant::class,
    'tenant_key' => 'id',
],

Integration Tips

Authentication

  • Sanctum: Use php artisan vendor:publish --tag="sanctum-config" to configure Sanctum.
  • Passport: Install Laravel Passport and configure the auth.driver to passport.
  • JWT: Use tyrimden/jwt-auth or similar for JWT-based auth.

Authorization

  • Integrate with Filament Shield or Spatie Laravel Permission:
    'authorization' => [
        'driver' => 'filament-shield', // or 'spatie-permission'
        'policies' => [
            Post::class => PostPolicy::class,
        ],
    ],
    

API Documentation

  • Use Scramjet (mentioned in README) or Laravel API Docs for auto-generated docs:
    composer require scramjet/laravel-api-docs
    
    Then configure in config/filament-api-service.php:
    'documentation' => [
        'enabled' => true,
        'provider' => \Scramjet\LaravelApiDocs\Providers\ApiDocsServiceProvider::class,
    ],
    

Testing

  • Use Laravel’s HTTP tests:
    public function test_api_endpoints()
    {
        $response = $this->actingAs(User::factory()->create())
                         ->getJson('/api/resources/posts');
        $response->assertOk();
    }
    

Gotchas and Tips

Pitfalls

  1. Middleware Conflicts

    • If API endpoints return 403 errors, check for conflicting middleware (e.g., auth:api vs. Filament’s auth).
    • Fix: Explicitly define middleware in getApiService() or adjust Filament’s panel middleware.
  2. Transformer Overrides

    • Forgetting to return the transformed data in transform() will result in empty responses.
    • Fix: Always return an array in the transformer:
      return ['key' => $resource->value];
      
  3. Query Builder Caching

    • Cached queries may not reflect real-time changes if using remember() or cache().
    • Fix: Disable caching for API endpoints or use ->withoutCache().
  4. Public Endpoints Security

    • Public endpoints ('public' => true) bypass authentication but may expose sensitive data.
    • Fix: Use transformers to sanitize data or restrict fields:
      'public_fields' => ['id', 'title'], // Only expose these fields
      
  5. Tenancy Misconfiguration

    • Tenant resolution may fail if the tenant_key or model is incorrect.
    • Fix: Verify tenancy setup with:
      \Stancl\Tenancy\Database\Models\Tenant::resolve();
      

Debugging Tips

  1. Log API Requests Add middleware to log requests:

    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Log;
    
    class LogApiRequests
    {
        public function handle($request, Closure $next)
        {
            Log::info('API Request', [
                'method' => $request->method(),
                'path' => $request->path(),
                'query' => $request->query(),
            ]);
            return $next($request);
        }
    }
    

    Register in config/filament-api-service.php:

    'middleware' => [
        \App\Http\Middleware\LogApiRequests::class,
    ],
    
  2. Check Generated Routes Dump routes to verify API endpoints:

    php artisan route:list | grep "api/resources"
    
  3. Validate Transformers Test transformers in isolation:

    $post = Post::first();
    $transformer = new PostTransformer();
    dd($transformer->transform($post));
    

Extension Points

  1. Custom API Actions Add custom API endpoints alongside CRUD:

    public static function getApiServiceActions(): array
    {
        return [
            'publish' => [
                'method' => 'PATCH',
                'path' => '/posts/{post}/publish',
                'handler' => [PostResource::class, 'publishPost'],
            ],
        ];
    }
    
    public static function publishPost($request, $post)
    {
        $post->update(['published_at' => now()]);
        return response()->json(['message' => 'Post published']);
    }
    
  2. Dynamic Base Path Override the base path per resource:

    public static function getApiService(): array
    {
        return [
            'base_path' => 'admin/api', // Override global setting
        ];
    }
    
  3. Event Listeners Hook into API events (e.g., ApiResourceCreated):

    namespace App\Listeners;
    
    use Rupadana\FilamentApiService\Events\ApiResourceCreated;
    
    class LogApiCreation
    {
        public function handle(ApiResourceCreated $event)
        {
            \Log::info('API Resource Created', ['id' => $event->resource->id]);
        }
    }
    

    Register in EventServiceProvider:

    protected $listen = [
        Api
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware