LaravelPackages.net
Acme Inc.
Toggle sidebar
marghoobsuleman/apiwizard

Generate Laravel models, relations, and APIs from an interactive command line

2
0
v1.0.1
About marghoobsuleman/apiwizard

marghoobsuleman/apiwizard is a Laravel package for generate laravel models, relations, and apis from an interactive command line. It currently has 0 GitHub stars and 2 downloads on Packagist (latest version v1.0.1). Install it with composer require marghoobsuleman/apiwizard. Discover more Laravel packages by marghoobsuleman or browse all Laravel packages to compare alternatives.

Last updated

APIWizard - Laravel API Generator

Latest Version on Packagist Total Downloads

A powerful Laravel package that generates models, relations, and complete REST APIs from an interactive command line interface or via command options.

✨ Features

  • 🎯 Interactive CLI - User-friendly prompts guide you through the generation process
  • πŸš€ Quick Generation - Create models, controllers, and routes in seconds
  • πŸ”— Automatic Relations - Define and generate model relationships effortlessly
  • πŸ”„ Safe Updates - Add relations to existing models without overwriting code
  • 🎨 Data Transformation - Optional transform methods for customizing API responses
  • πŸ“¦ Complete REST API - Generates full CRUD endpoints automatically
  • βš™οΈ Non-Interactive Mode - Use command options for automation and scripting
  • πŸ› οΈ Customizable - Publish and modify stubs to match your coding style
  • πŸ“ PSR-4 Compliant - Follows Laravel and PHP best practices

πŸ“‹ Requirements

  • PHP 8.2 or higher
  • Laravel 11.x or 12.x

πŸ“¦ Installation

Install the package via Composer:

composer require marghoobsuleman/apiwizard

The package will automatically register its service provider.

Publish Configuration (Optional)

php artisan vendor:publish --tag=apiwizard-config

Publish Stubs (Optional)

php artisan vendor:publish --tag=apiwizard-stubs

πŸš€ Usage

Available Commands

The package provides two commands (both work identically):

php artisan apiwizard:generate
# OR
php artisan modelwizard:generate

Interactive Mode

Run the command and follow the prompts:

php artisan apiwizard:generate

Example Interactive Session:

πŸ§™ APIWizard - Laravel API Generator

Enter table name: users
Model name will be: User

Does it have any relations? (yes/no): yes
Enter related table name: posts
Type of relation:
  [0] hasOne
  [1] hasMany
  [2] belongsTo
  [3] belongsToMany
 > 1

βœ“ Added hasMany relation with posts

Add another relation? (yes/no): no

Do you want to modify returned data (add transform method)? (yes/no): yes

Do you want to create an API endpoint? (yes/no): yes
Enter API endpoint [/api/users]: /api/users

πŸ”¨ Generating files...

βœ“ Model created: /app/Models/User.php
βœ“ Related model created: /app/Models/Post.php
βœ“ Controller created: /app/Http/Controllers/API/UserController.php
βœ“ Routes added to: routes/api.php

βœ… Generation completed successfully!

Non-Interactive Mode

Use command options for automation:

php artisan apiwizard:generate --table=users --relations=posts:hasMany --endpoint=/api/users --transform

Available Options:

| Option | Description | Example | |--------|-------------|---------| | --table | Table name (required for non-interactive) | --table=users | | --relations | Relations in format "table:type" (can be used multiple times) | --relations=posts:hasMany --relations=profile:hasOne | | --endpoint | API endpoint path | --endpoint=/api/users | | --transform | Include transform method in model | --transform | | --no-api | Skip API generation (model only) | --no-api |

Examples:

Generate model with multiple relations:

php artisan apiwizard:generate \
  --table=users \
  --relations=posts:hasMany \
  --relations=profile:hasOne \
  --relations=roles:belongsToMany \
  --endpoint=/api/users \
  --transform

Generate model without API:

php artisan apiwizard:generate --table=products --no-api

Simple model with API:

php artisan apiwizard:generate --table=categories --endpoint=/api/categories

πŸ“š What Gets Generated

1. Model File

Generated at app/Models/{ModelName}.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasFactory;

    protected $table = 'users';
    
    protected $fillable = [
        // Add your fillable attributes here
    ];

    // Relations
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    // Transform method (if requested)
    public function transform(): array
    {
        return [
            'id' => $this->id,
            // Add your custom transformations here
        ];
    }
}

2. Controller File

Generated at app/Http/Controllers/API/{ModelName}Controller.php:

<?php

namespace App\Http\Controllers\API;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function index()
    {
        $users = User::paginate(15);
        
        return response()->json([
            'success' => true,
            'data' => $users->map(fn($item) => $item->transform()),
            'pagination' => [
                'total' => $users->total(),
                'per_page' => $users->perPage(),
                'current_page' => $users->currentPage(),
                'last_page' => $users->lastPage(),
            ],
        ]);
    }

    public function show($id)
    {
        $user = User::findOrFail($id);
        
        return response()->json([
            'success' => true,
            'data' => $user->transform(),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            // Add your validation rules here
        ]);

        $user = User::create($validated);
        
        return response()->json([
            'success' => true,
            'message' => 'User created successfully',
            'data' => $user,
        ], 201);
    }

    public function update(Request $request, $id)
    {
        $user = User::findOrFail($id);
        
        $validated = $request->validate([
            // Add your validation rules here
        ]);

        $user->update($validated);
        
        return response()->json([
            'success' => true,
            'message' => 'User updated successfully',
            'data' => $user,
        ]);
    }

    public function destroy($id)
    {
        $user = User::findOrFail($id);
        $user->delete();
        
        return response()->json([
            'success' => true,
            'message' => 'User deleted successfully',
        ]);
    }
}

3. API Routes

Added to routes/api.php:

// UserController routes
Route::apiResource('users', \App\Http\Controllers\API\UserController::class);

This creates the following endpoints:

  • GET /api/users - List all users (paginated)
  • POST /api/users - Create a new user
  • GET /api/users/{id} - Show a specific user
  • PUT/PATCH /api/users/{id} - Update a user
  • DELETE /api/users/{id} - Delete a user

βš™οΈ Configuration

After publishing the config file, you can customize:

return [
    // Model namespace
    'model_namespace' => 'App\\Models',

    // Controller namespace
    'controller_namespace' => 'App\\Http\\Controllers\\API',

    // Model path
    'model_path' => app_path('Models'),

    // Controller path
    'controller_path' => app_path('Http/Controllers/API'),

    // Routes file
    'routes_file' => base_path('routes/api.php'),

    // Default pagination
    'pagination' => 15,
];

🎨 Customizing Stubs

Publish the stubs and modify them to match your preferences:

php artisan vendor:publish --tag=apiwizard-stubs

Stubs will be published to stubs/apiwizard/:

  • model.stub - Model template
  • controller.stub - Controller template

πŸ”— Supported Relation Types

  • hasOne - One-to-one relationship
  • hasMany - One-to-many relationship
  • belongsTo - Inverse of one-to-many
  • belongsToMany - Many-to-many relationship

πŸ’‘ Tips & Best Practices

  1. Always review generated code - The package creates a solid foundation, but you should review and customize:

    • Add proper validation rules in controllers
    • Define fillable/guarded attributes in models
    • Customize transform methods for your API responses
  2. Use transform methods - They provide a clean way to control API output without cluttering controllers

  3. Leverage non-interactive mode - Perfect for:

    • CI/CD pipelines
    • Seeding multiple models
    • Scripted setups
  4. Customize stubs - Publish and modify stubs to match your team's coding standards

πŸ§ͺ Testing

Run the tests with:

composer test

πŸ“ Changelog

Please see CHANGELOG for more information on what has changed recently.

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ”’ Security

If you discover any security-related issues, please email [email protected] instead of using the issue tracker.

πŸ“„ License

The MIT License (MIT). Please see License File for more information.

πŸ‘ Credits

🌟 Support

If you find this package helpful, please consider giving it a ⭐️ on GitHub!


Made with ❀️ for the Laravel community

Comments