DEV Community

Cover image for Laravel Auto CRUD Generator: Save 8+ Hours Per Project
Putra Prima A
Putra Prima A

Posted on

Laravel Auto CRUD Generator: Save 8+ Hours Per Project

Tired of writing repetitive CRUD code? This tool generates it all in 30 seconds.

Ever found yourself writing the same controllers, requests, and views over and over again for each model in your Laravel project? What if I told you there's a way to automate all of that tedious work with just a single command? Keep reading to discover how you can save hours of development time on every project.

🚀 What Is Laravel Auto CRUD Generator?

Laravel Auto CRUD Generator is a powerful package that revolutionizes how you handle CRUD (Create, Read, Update, Delete) operations in your Laravel applications. Instead of manually coding controllers, requests, routes, and views for each model, this package generates everything automatically.

With a single command, you can have a fully functional CRUD implementation for any model in your application. This means you can focus on building the unique aspects of your application rather than writing boilerplate code.

💡 Why You Need This In Your Development Toolkit

Let's be honest - writing CRUD operations is necessary but repetitive. For each new model, you typically need to:

  1. Create a controller with 7 methods (index, create, store, show, edit, update, destroy)
  2. Build validation requests
  3. Set up API resources if you're building an API
  4. Configure routes
  5. Create views for each action
  6. Implement repositories and services if you follow that pattern

That's a lot of work! And it's the same pattern repeated for every single model in your application.

Laravel Auto CRUD Generator completely eliminates this repetitive work.

✨ Impressive Features That Will Transform Your Workflow

The package comes loaded with features designed to make your development experience smoother:

🔍 Smart Model Detection

The package automatically scans your app/Models folder to find all available models, saving you from having to remember and type model names manually.

💻 Interactive CLI Experience

Enjoy a friendly command-line interface that guides you through the generation process, making it accessible even for those new to Laravel.

🏗️ Complete Code Generation

It doesn't just create basic templates - it generates fully functional:

  • Controllers (for both web and API)
  • Request validation classes
  • Resource classes for API responses
  • Routes configured and ready to use
  • Views with proper forms and listings
  • Repositories and services (if you use that pattern)

🔄 Multiple Architecture Support

Whether you prefer:

  • Standard Laravel controllers
  • Repository pattern implementation
  • Service layer architecture
  • Spatie Data integration

The package has you covered with code generated specifically for your preferred architecture style.

🌐 API Development Support

Building an API? The package generates:

  • API controllers with proper status codes
  • JSON resources for standardized responses
  • Optional CURL command examples
  • Postman collection export

📚 Best Practices Compliance

All generated code follows Laravel's best practices for clean and maintainable code, so you don't have to worry about technical debt.

🛠️ How To Install and Configure

Getting started with Laravel Auto CRUD Generator is straightforward:

  1. Install the package via Composer:
composer require mrmarchone/laravel-auto-crud --dev
Enter fullscreen mode Exit fullscreen mode
  1. Publish the configuration file to customize the generator:
php artisan vendor:publish --provider="Mrmarchone\LaravelAutoCrud\LaravelAutoCrudServiceProvider" --tag="auto-crud-config"
Enter fullscreen mode Exit fullscreen mode

That's it! You're ready to start generating CRUD operations.

🔥 Using Laravel Auto CRUD Generator

The magic happens with a single Artisan command:

php artisan auto-crud:generate
Enter fullscreen mode Exit fullscreen mode

This command provides several options to customize the generation process:

Options:
  -M, --model[=MODEL]             Select one or more of your models
  -T, --type[=TYPE]               Select whether to generate API or web controllers
  -R, --repository                Work with repository design pattern
  -O, --overwrite                 Overwrite existing files
  -P, --pattern[=PATTERN]         Support for Spatie-Data Pattern
  -C, --curl                      Generate CURL requests for API
  -MP, --model-path[=MODEL-PATH]  Set custom models path
  -PM, --postman                  Generate Postman Collection for API
Enter fullscreen mode Exit fullscreen mode

Example Command

Here's a comprehensive example:

php artisan auto-crud:generate --model-path=app/AnotherModels --model=User --model=Manager --overwrite --type=api --repository --pattern=spatie-data --curl --postman
Enter fullscreen mode Exit fullscreen mode

This command will:

  1. Look for models in the app/AnotherModels directory
  2. Generate CRUD operations for both User and Manager models
  3. Overwrite any existing files
  4. Create API controllers instead of web controllers
  5. Implement the repository pattern
  6. Use Spatie's Data pattern
  7. Generate CURL examples
  8. Create a Postman collection

📊 What Gets Generated?

Let's look at what files the package creates for a User model:

1. API Controller

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Requests\UserRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class UserController extends Controller
{
    public function index(): \Illuminate\Http\Resources\Json\AnonymousResourceCollection
    {
        return UserResource::collection(User::latest()->paginate(10));
    }

    public function store(UserRequest $request): UserResource|\Illuminate\Http\JsonResponse
    {
        try {
            $user = User::create($request->validated());
            return new UserResource($user);
        } catch (\Exception $exception) {
            report($exception);
            return response()->json(['error' => 'There is an error.'], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function show(User $user): UserResource
    {
        return UserResource::make($user);
    }

    public function update(UserRequest $request, User $user): UserResource|\Illuminate\Http\JsonResponse
    {
        try {
            $user->update($request->validated());
            return new UserResource($user);
        } catch (\Exception $exception) {
            report($exception);
            return response()->json(['error' => 'There is an error.'], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function destroy(User $user): \Illuminate\Http\JsonResponse
    {
        try {
            $user->delete();
            return response()->json(['message' => 'Deleted successfully'], Response::HTTP_NO_CONTENT);
        } catch (\Exception $exception) {
            report($exception);
            return response()->json(['error' => 'There is an error.'], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Web Controller

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Requests\UserRequest;
use App\Models\User;

class UserController extends Controller
{
    public function index(): \Illuminate\Contracts\View\View
    {
        $users = User::latest()->paginate(10);
        return view('users.index', compact('users'));
    }

    public function create(): \Illuminate\Contracts\View\View
    {
        return view('users.create');
    }

    public function store(UserRequest $request): \Illuminate\Http\RedirectResponse
    {
        User::create($request->validated());
        return redirect()->route('users.index')->with('success', 'Created successfully');
    }

    public function show(User $user): \Illuminate\Contracts\View\View
    {
        return view('users.show', compact('user'));
    }

    public function edit(User $user): \Illuminate\Contracts\View\View
    {
        return view('users.edit', compact('user'));
    }

    public function update(UserRequest $request, User $user): \Illuminate\Http\RedirectResponse
    {
        $user->update($request->validated());
        return redirect()->route('users.index')->with('success', 'Updated successfully');
    }

    public function destroy(User $user): \Illuminate\Http\RedirectResponse
    {
        $user->delete();
        return redirect()->route('users.index')->with('success', 'Deleted successfully');
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Validation Request

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|string|max:255|unique:users,email',
            'email_verified_at' => 'nullable|date',
            'password' => 'required|string|max:255',
            'remember_token' => 'nullable|string|max:100',
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

4. API Resource

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'email_verified_at' => $this->email_verified_at,
            'password' => $this->password,
            'remember_token' => $this->remember_token,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Routes

The package also generates routes in both web.php and api.php files:

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

// web.php
Route::resource('/users', App\Http\Controllers\UserController::class);
Enter fullscreen mode Exit fullscreen mode

6. Repository and Service (if enabled)

When using the repository pattern, it generates properly structured repository and service classes:

<?php
namespace App\Repositories;

use App\Models\User;

class UserRepository
{
    // Repository implementation
}
Enter fullscreen mode Exit fullscreen mode
<?php
namespace App\Services;

use App\Models\User;
use App\Repositories\UserRepository;

class UserService
{
    // Service implementation
}
Enter fullscreen mode Exit fullscreen mode

7. Spatie Data (if enabled)

<?php

namespace App\Data;

use Spatie\LaravelData\Data;
use Spatie\LaravelData\Attributes\Validation\Max;
use Spatie\LaravelData\Attributes\Validation\Unique;
use Spatie\LaravelData\Attributes\Validation\Date;
use Carbon\Carbon;

class UserData extends Data
{
    #[Max(255)]
    public string $name;
    #[Max(255), Unique('users', 'email')]
    public string $email;
    #[Date]
    public ?Carbon $email_verified_at;
    #[Max(255)]
    public string $password;
    #[Max(100)]
    public ?string $remember_token;
}
Enter fullscreen mode Exit fullscreen mode

⚠️ Important Notes

When working with models outside the default app/Models directory, the command will generate files following your custom directory structure. For example:

If you use --model-path=app/AnotherModels/Models, it will generate controllers at app/Http/Controllers/AnotherModels/Models/ModelController.php.

🌟 Real-World Impact

Let's put this in perspective:

Without Laravel Auto CRUD Generator:

  • Creating CRUD operations for 10 models: ~10 hours
  • Implementing repository pattern: +5 hours
  • Setting up API resources and proper error handling: +3 hours
  • Total: ~18 hours of repetitive coding

With Laravel Auto CRUD Generator:

  • Setting up the package: 5 minutes
  • Running the command for 10 models: 5 minutes
  • Review and minor adjustments: 30 minutes
  • Total: ~40 minutes

That's a time saving of over 17 hours on a single project! 🤯

🧰 Requirements

To use Laravel Auto CRUD Generator, you need:

  • Laravel 10+
  • PHP 8.1+
  • Laravel Data Spatie (optional, only if using the Spatie Data pattern)

🚀 Take Your Laravel Development to the Next Level

By adding Laravel Auto CRUD Generator to your toolkit, you'll:

  1. Save hours of development time on every project
  2. Reduce bugs by using consistently generated code
  3. Maintain clean architecture across your entire application
  4. Focus on building unique features rather than repetitive CRUD operations

🙋‍♂️ Ready to supercharge your Laravel development?

If you're tired of writing the same CRUD code over and over again, it's time to try Laravel Auto CRUD Generator.

Who's with me? Drop a comment below if you're going to give this a try on your next project! I'd love to hear how many hours it saves you.

Check out more developer tools and tutorials on:

Raise your hand if you're ready to save 8+ hours on your next Laravel project!

Top comments (0)