tgozo/laravel-codegen

A Laravel Code Generator to help you get started with a lot of staff including generating Migrations, Models, Controllers, Factories, Routes, Views, Database Seeders and Request Validation Rules.

Installs: 135

Dependents: 0

Suggesters: 0

Security: 0

Stars: 12

Watchers: 6

Forks: 1

Open Issues: 0

pkg:composer/tgozo/laravel-codegen

1.0.9 2024-08-22 12:34 UTC

This package is auto-updated.

Last update: 2025-10-20 09:45:12 UTC


README

Latest Version on Packagist Total Downloads License

Stop writing boilerplate code. Start building features.

Laravel CodeGen is a powerful code generation package that transforms your development workflow by automatically generating complete, production-ready Laravel components with a single command. Say goodbye to repetitive coding and hello to blazing-fast development!

โœจ Why Laravel CodeGen?

  • ๐Ÿƒโ€โ™‚๏ธ 10x Faster Development: Generate complete CRUD operations in seconds, not hours
  • ๐ŸŽฏ Zero Configuration: Works out of the box with sensible defaults
  • ๐Ÿ”ง Highly Configurable: Customize every aspect of generated code to match your standards
  • ๐Ÿงช Test-Driven: Automatically generates comprehensive Pest PHP tests
  • ๐Ÿ“ฑ Modern Stack Support: Built-in Livewire components with Alpine.js integration
  • ๐Ÿ”„ Reverse Engineering: Convert existing databases to Laravel code instantly
  • ๐ŸŽจ Consistent Code Quality: Follows Laravel best practices and coding standards

๐Ÿ”ฅ Features That Will Blow Your Mind

๐ŸŽช Complete Application Scaffolding

Generate entire application modules with a single command:

  • ๐Ÿ“‹ Database Migrations - With intelligent field types and relationships
  • ๐Ÿ“ฆ Eloquent Models - Including relationships, casts, and factory integration
  • ๐ŸŽฎ Controllers - Full CRUD operations with proper validation
  • ๐Ÿญ Model Factories - Smart fake data generation using AI-powered field detection
  • ๐ŸŒฑ Database Seeders - Pre-populated with realistic test data
  • ๐Ÿš Routes - RESTful routes with proper naming conventions
  • ๐Ÿ‘€ Blade Views - Beautiful, responsive UI components
  • โšก Livewire Components - Modern, reactive components (Create, Read, Update, Delete)
  • ๐Ÿงช Pest PHP Tests - Comprehensive test coverage for all endpoints
  • ๐Ÿ“ Form Requests - Robust validation with custom rules

๐Ÿ”„ Reverse Engineering Magic

Already have a database? No problem!

# Convert your entire database to Laravel code
php artisan codegen:reverse-engineer --all

# Generate models only
php artisan codegen:reverse-engineer --models

# Target specific tables
php artisan codegen:reverse-engineer --tables=users,posts --all

Supports multiple databases: MySQL, PostgreSQL, SQLite

๐ŸŽจ Smart Code Generation

  • Intelligent Field Detection: Automatically detects field types and generates appropriate form inputs
  • Relationship Inference: Discovers and generates model relationships automatically
  • Faker Integration: Uses advanced algorithms to generate realistic fake data
  • Validation Rules: Auto-generates validation rules based on database constraints
  • Consistent Naming: Follows Laravel naming conventions perfectly

๐Ÿ“ฆ Requirements

  • PHP >= 8.1
  • Laravel >= 10.0
  • Composer 2.0+

โšก Quick Installation

composer require tgozo/laravel-codegen

That's it! The package auto-registers itself. No additional setup required.

Optional: Publish Configuration

php artisan vendor:publish --provider="Tgozo\LaravelCodegen\CodeGenServiceProvider"

๐Ÿš€ Usage Examples

๐ŸŽฏ Quick Start - Complete CRUD in 30 Seconds

# Generate everything for a blog post system
php artisan make:codegen-migration create_posts_table --all

This single command creates:

  • โœ… Migration with intelligent field prompts
  • โœ… Post model with relationships and casts
  • โœ… PostController with full CRUD operations
  • โœ… PostFactory with realistic fake data
  • โœ… Database seeder
  • โœ… 4 Livewire components (View, Show, Create, Edit)
  • โœ… RESTful routes
  • โœ… Responsive Blade views
  • โœ… Complete Pest PHP test suite (12+ tests)
  • โœ… Form request validation

๐ŸŽช Selective Generation

# Just migration, model, and factory
php artisan make:codegen-migration create_users_table -mf

# Migration, model, controller, and seeder
php artisan make:codegen-migration create_products_table -mcs

# Everything with Livewire components
php artisan make:codegen-migration create_orders_table -mcsfp --livewire

๐Ÿ”„ Reverse Engineer Existing Database

# Convert entire database
php artisan codegen:reverse-engineer --all

# Only specific tables
php artisan codegen:reverse-engineer --tables=users,posts,comments --models

# With custom connection
php artisan codegen:reverse-engineer --connection=legacy --all

๐ŸŽจ Advanced Field Configuration

During migration creation, you can specify complex field types:

Field name: title
Field type: string:nullable:unique:index

Field name: price
Field type: decimal:precision:10,2:default:0.00

Field name: user_id
Field type: foreignId:constrained:cascadeOnDelete

๐Ÿ› ๏ธ Command Options

Option Description
-m, --model Generate Eloquent model
-c, --controller Generate controller with CRUD operations
-f, --factory Generate model factory
-s, --seeder Generate database seeder
-p, --pest Generate Pest PHP tests
-l, --livewire Generate Livewire components
--all Generate everything (equivalent to -mcsfpl)
--force Overwrite existing files
--relates Specify model relationships
--except Exclude specific generations

๐ŸŽญ Generated Code Examples

๐Ÿ“ฆ Eloquent Model

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * Using $guarded = [] instead of $fillable for models with many fields
     * This approach is more maintainable for models with 18+ fields
     * and provides better security against mass-assignment vulnerabilities.
     */
    protected $guarded = [];

    protected $casts = [
        'published_at' => 'datetime',
        'is_featured' => 'boolean',
        'metadata' => 'array',
    ];

    // Relationships are auto-generated
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

๐ŸŽฎ Controller with CRUD

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use Illuminate\Http\Controller;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::with('user')->paginate(15);
        return view('posts.index', compact('posts'));
    }

    public function store(StorePostRequest $request)
    {
        $post = Post::create($request->validated());
        return redirect()->route('posts.show', $post)
            ->with('success', 'Post created successfully!');
    }

    // ... other CRUD methods
}

โšก Livewire Component

<?php

namespace App\Livewire\Post;

use App\Models\Post;
use Livewire\Component;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;

class Create extends Component
{
    public string $title = '';
    public string $content = '';
    public bool $is_published = false;

    protected $rules = [
        'title' => 'required|min:3|max:255',
        'content' => 'required|min:10',
        'is_published' => 'boolean',
    ];

    public function save()
    {
        $this->validate();
        
        Post::create([
            'title' => $this->title,
            'content' => $this->content,
            'is_published' => $this->is_published,
            'user_id' => auth()->id(),
        ]);

        session()->flash('success', 'Post created successfully!');
        return redirect()->route('posts.index');
    }

    #[Title('Create Post')]
    #[Layout('layouts.app')]
    public function render()
    {
        return view('livewire.post.create');
    }
}

๐Ÿงช Pest PHP Tests

<?php

use App\Models\Post;
use App\Models\User;

beforeEach(function () {
    $this->user = User::factory()->create();
    $this->actingAs($this->user);
});

it('can display posts index page', function () {
    Post::factory(3)->create();
    
    $this->get(route('posts.index'))
        ->assertOk()
        ->assertViewIs('posts.index')
        ->assertViewHas('posts');
});

it('can create a new post', function () {
    $postData = [
        'title' => 'Test Post',
        'content' => 'This is a test post content.',
        'is_published' => true,
    ];
    
    $this->post(route('posts.store'), $postData)
        ->assertRedirect()
        ->assertSessionHas('success');
    
    $this->assertDatabaseHas('posts', $postData);
});

// ... 10+ more tests covering all scenarios

๐ŸŽจ Configuration

Publishing Configuration

php artisan vendor:publish --provider="Tgozo\LaravelCodegen\CodeGenServiceProvider"

Configuration Options

<?php

return [
    // Choose between 'controller' or 'livewire' for generated logic
    'logic_preference' => 'livewire',
    
    // Default namespace for generated classes
    'default_namespace' => 'App',
    
    // Custom stub paths
    'stub_paths' => [
        // Override default stubs with your custom ones
    ],
    
    // Test framework preference
    'test_framework' => 'pest', // or 'phpunit'
    
    // View framework preference
    'view_framework' => 'livewire', // or 'blade'
];

๐ŸŽญ Migration Patterns

The package supports various migration patterns:

Pattern Description Example
create_{table}_table Create new table create_posts_table
add_{columns}_to_{table}_table Add columns add_featured_to_posts_table
drop_{columns}_from_{table}_table Remove columns drop_legacy_from_users_table
modify_{table}_table Modify existing table modify_posts_table

๐Ÿ”ง Advanced Features

๐Ÿค– AI-Powered Field Detection

The package includes intelligent field type detection:

// Automatically detects appropriate faker methods
'email' => fake()->unique()->safeEmail(),
'phone' => fake()->phoneNumber(),
'address' => fake()->address(),
'birth_date' => fake()->dateTimeBetween('-50 years', '-18 years'),
'avatar' => fake()->imageUrl(200, 200, 'people'),

๐Ÿ”— Relationship Management

# Specify relationships during generation
php artisan make:codegen-migration create_posts_table --relates="user:belongsTo,comments:hasMany"

๐Ÿ“ฑ Livewire Integration

Generated Livewire components include:

  • Real-time validation
  • Loading states
  • Error handling
  • Success messages
  • Responsive design
  • Alpine.js integration

๐Ÿงช Testing

The package generates comprehensive test suites:

# Run generated tests
php artisan test

# Or with Pest
vendor/bin/pest

Generated tests cover:

  • โœ… Route accessibility
  • โœ… CRUD operations
  • โœ… Validation rules
  • โœ… Authorization policies
  • โœ… Database constraints
  • โœ… Model relationships
  • โœ… Factory generation
  • โœ… Seeder execution

๐Ÿค Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.

Development Setup

git clone https://github.com/tgozo/laravel-codegen.git
cd laravel-codegen
composer install
vendor/bin/pest

๐Ÿ“ˆ Roadmap

  • GraphQL Integration - Generate GraphQL schemas and resolvers
  • API Documentation - Auto-generate OpenAPI/Swagger docs
  • Docker Integration - Generate Docker configurations
  • Queue Jobs - Generate background job classes
  • Event/Listener System - Generate event-driven architectures
  • Multi-tenancy Support - Generate tenant-aware models and migrations
  • Custom Stubs Manager - GUI for managing custom stubs

๐Ÿ›ก๏ธ Security

If you discover any security-related issues, please email dev@tgozo.co.zw instead of using the issue tracker.

๐Ÿ“„ License

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

๐Ÿ™ Credits

  • Takudzwa Gozo - GitHub
  • All Contributors - Thank you for making this package better!

โญ If this package saved you time, please consider giving it a star! โญ

Report Bug โ€ข Request Feature โ€ข Documentation