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

Auto Api Laravel Package

fariddomat/auto-api

Laravel package that generates complete REST API modules via an interactive Artisan command: models, migrations, controllers, routes, and OpenAPI docs. Supports file uploads, pagination, soft deletes, searchable fields, and select-field relationships.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require fariddomat/auto-api:dev-main in your Laravel project. No additional configuration is required—the package auto-registers its command.

  2. First Command Execute php artisan make:auto-api to launch the interactive CLI. Follow prompts to define:

    • Model name (e.g., Product).
    • Fields (e.g., name:string, category_id:select).
    • API version (defaults to v1).
    • Optional features (soft deletes, search, middleware).
  3. First Use Case Generate a CRUD API for a Product model with name (string) and category_id (select). The package creates:

    • Model + Migration (app/Models/Product.php, database/migrations/..._create_products_table.php).
    • Controller (app/Http/Controllers/API/V1/ProductController.php).
    • Routes (routes/api.php).
    • OpenAPI spec (api/openapi/v1/product.yaml).

Implementation Patterns

Workflows

  1. Iterative Development Use make:auto-api repeatedly to scaffold APIs incrementally. For example:

    • Start with core fields (name:string, price:decimal).
    • Later, add image:image or description:text via the same command (fields are appended to existing migrations/models).
  2. Relationship Handling For select fields (e.g., category_id:select), the package:

    • Auto-generates a belongsTo relationship in the model.
    • Includes the related data in API responses (e.g., { "category": { "id": 1, "name": "Electronics" } }).
    • Tip: Pre-generate the related model (e.g., Category) first to avoid errors.
  3. API Versioning Specify a version (e.g., v2) to generate routes under routes/api.php with versioned prefixes:

    Route::prefix('v2')->group(function () {
        // Auto-generated routes for v2
    });
    
  4. Middleware Integration Assign middleware (e.g., auth:api) during generation. The package injects middleware into the route group:

    Route::middleware(['auth:api'])->group(function () {
        // Routes...
    });
    
  5. OpenAPI Documentation Generated specs (api/openapi/v1/product.yaml) follow OpenAPI 3.0. Use tools like Swagger UI to visualize the API:

    npm install @openapitools/openapi-generator-cli -g
    openapi-generator-cli generate -i api/openapi/v1/product.yaml -g swagger-ui -o public/docs
    

Integration Tips

  • Existing Models To extend an existing model, manually add fields to the migration/model, then regenerate the controller/routes via:

    php artisan make:auto-api --model=Product --force
    

    Note: The --force flag overwrites existing API files.

  • Custom Validation Override the auto-generated controller’s rules() method to add custom validation:

    public function rules()
    {
        return array_merge(parent::rules(), [
            'price' => 'required|min:0',
        ]);
    }
    
  • File Uploads For image:image fields, the package handles:

    • File upload logic in the controller.
    • Storage path configuration (default: storage/app/public). Customize storage in config/filesystems.php or override the controller’s uploadPath() method.
  • Search Functionality Enable search with searchable_fields (e.g., name). The package adds a search query parameter to routes and implements search logic in the controller using Laravel’s where clauses.


Gotchas and Tips

Pitfalls

  1. Field Name Conflicts Avoid reserved Laravel keywords (e.g., created_at) as field names. The package may fail silently or generate malformed migrations.

  2. Relationship Loops Circular relationships (e.g., Product has category_id:select and Category has product_id:select) can cause infinite recursion in API responses. Explicitly define with() in the controller or use hidden() in the model:

    protected $hidden = ['pivot'];
    
  3. Migration Conflicts Regenerating a model’s API after manual migration changes may cause conflicts. Use --force cautiously:

    php artisan make:auto-api --model=Product --force
    

    Tip: Backup migrations before forcing updates.

  4. OpenAPI Schema Issues Complex relationships (e.g., polymorphic) may not render correctly in OpenAPI specs. Manually edit the generated YAML or extend the toOpenApiSchema() method in the model.

  5. Middleware Overrides If middleware is added post-generation, update the route file manually or regenerate the API with the correct middleware flags.

Debugging

  • CLI Errors Check the package’s service provider (vendor/fariddomat/auto-api/src/ServiceProvider.php) for registration issues. Ensure no naming collisions with existing commands.

  • Route Conflicts Auto-generated routes may clash with manual routes. Use php artisan route:list to debug and adjust route namespaces/prefixes.

  • File Upload Failures Verify:

    • The image field’s column type in the migration (e.g., string for file paths).
    • Storage disk is configured in config/filesystems.php.
    • The public symlink exists (php artisan storage:link).

Tips

  1. Partial Regeneration To update only the controller/routes (not the model/migration), use:

    php artisan make:auto-api --model=Product --skip-model
    
  2. Testing Auto-generated APIs include basic tests in tests/Feature/API/. Extend them with:

    public function test_custom_validation()
    {
        $response = $this->postJson('/api/v1/products', [
            'name' => 'Test',
            'price' => -1, // Invalid
        ]);
        $response->assertUnprocessable();
    }
    
  3. Extending Functionality Override the package’s generators by publishing and modifying its templates:

    php artisan vendor:publish --tag=auto-api-templates
    

    Edit files in resources/views/vendor/auto-api/.

  4. Soft Deletes When enabled, the package adds:

    • deleted_at column to the migration.
    • withTrashed() to queries in the controller. Ensure your App\Models\Model extends Illuminate\Database\Eloquent\Model (not SoftDeletes directly).
  5. Performance For large datasets, disable eager loading in the controller’s with() method or use loadMissing():

    public function index()
    {
        return Product::with(['category'])->paginate(10);
        // OR for lazy loading:
        // return Product::paginate(10)->loadMissing('category');
    }
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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