laravelphptutorialcrud

Generate a Laravel CRUD App with AI

Build a complete Laravel application with Eloquent models, Blade templates, and CRUD operations from a single text prompt. Full walkthrough with LoomCode AI.

LoomCode AI Team13 min read

Laravel Development, Reimagined

Building CRUD applications in Laravel involves creating models, migrations, controllers, routes, and Blade templates — a lot of boilerplate before you see results. Even experienced Laravel developers spend significant time wiring up the same patterns: define a model, write a migration, scaffold a controller with validation logic, register routes, and build out Blade views with forms and error handling. For a single resource, that can easily mean touching six or more files before the first page renders.

LoomCode AI generates all of this from a description, letting you focus on business logic instead of scaffolding. You describe what the application should do in plain English, and the AI produces a working Laravel project with properly structured directories, PSR-4 autoloading, and idiomatic code that follows the conventions Laravel developers expect.

This approach is particularly effective for Laravel because the framework is so convention-driven. The AI can infer route names from model names, generate the correct Eloquent relationships, and produce Blade templates that use the right directives — all from a concise prompt.

What We'll Build

A task management application with:

  • Task model with title, description, status, priority, and due date
  • Full CRUD operations (create, read, update, delete)
  • Blade templates with a clean UI
  • Status filtering (pending, in-progress, completed)
  • Priority sorting
  • Form validation

This is a realistic starting point for many internal tools, project trackers, and workflow apps. The generated code is meant to be a working foundation you can extend, not a throwaway prototype.

How AI Understands Laravel Conventions

One of the reasons Laravel works so well with AI code generation is its strong conventions. The framework has opinionated defaults for nearly everything — naming, directory structure, database patterns, routing — and modern AI models have been trained extensively on Laravel codebases that follow these patterns.

When you prompt LoomCode AI with a Laravel project, it draws on its understanding of:

  • MVC architecture — Models go in app/Models, controllers in app/Http/Controllers, views in resources/views. The AI follows this structure automatically.
  • Eloquent ORM — The AI generates models with proper $fillable arrays, $casts definitions, relationship methods, and query scopes. It knows that a belongsTo relationship on a Task model expects a user_id foreign key by convention.
  • Migrations — Column types, nullable fields, indexes, foreign key constraints, and default values are generated correctly. The AI understands the difference between string, text, and enum columns and chooses appropriately.
  • Blade templating — Directives like @csrf, @method('PUT'), @error, @foreach, and @extends are used correctly. The AI generates layouts with @yield and child views with @section.
  • Route model binding — Instead of manually fetching models by ID in controller methods, the AI uses implicit route model binding by type-hinting the model in method signatures.
  • Form requests — For complex validation, the AI can generate dedicated form request classes rather than inline validation arrays.

You get better results when you mention these conventions explicitly in your prompt. For example, instead of saying "add filtering," say "add Eloquent query scopes for filtering by status." Instead of "add login," say "add Laravel Breeze authentication." The more framework-specific your language, the more idiomatic the output.

The Prompt

Select the Laravel template on LoomCode AI and enter:

Build a task management app with:
- Task model with: title (required), description (text), status (pending/in-progress/completed), priority (low/medium/high), due_date
- SQLite database with migration
- Full CRUD: list all tasks, create new task, edit task, delete task
- List page with status filter tabs and priority sorting
- Blade templates with a clean, modern UI using Tailwind CSS
- Form validation for required fields
- Flash messages for success/error

A few things to note about this prompt. Specifying the column types and enum values explicitly (like pending/in-progress/completed) removes ambiguity and ensures the migration matches your expectations. Mentioning Tailwind CSS tells the AI which styling approach to use. Requesting flash messages ensures the generated controllers include redirect logic with session data.

What Gets Generated

LoomCode AI creates a complete Laravel 11+ application:

Routes

A resourceful route setup in routes/web.php mapping all CRUD operations to controller methods. This typically uses Route::resource('tasks', TaskController::class), which automatically registers all seven RESTful routes with proper naming conventions like tasks.index, tasks.store, tasks.update, and so on.

Eloquent Model

A Task model with fillable attributes, casts for dates, and scope methods for filtering by status. The model includes a $fillable array to protect against mass assignment, date casting for the due_date field, and local scopes like scopeByStatus that make filtering chainable and reusable across controllers and views.

Migration

A database migration creating the tasks table with all fields, proper column types, and indexes. Enum columns are used for status and priority to enforce valid values at the database level. Indexes are added on columns that will be filtered or sorted frequently.

Controller

A TaskController with all 7 RESTful methods: index, create, store, show, edit, update, destroy — complete with validation and redirect logic. Each method follows Laravel conventions: returning views for GET requests, validating and persisting data for POST/PUT requests, and redirecting with flash messages after mutations.

Blade Templates

Clean, styled templates for:

  • List view — Tasks displayed in cards with status badges and priority indicators, with tab navigation for filtering
  • Create/Edit forms — Form inputs with validation error display using @error directives and old input repopulation via old()
  • Layout — A base layout with navigation, Tailwind CSS, and flash message support using @if(session('success')) blocks

Example Generated Code

Here is what the generated migration looks like for the tasks table:

Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('description')->nullable();
    $table->enum('status', ['pending', 'in-progress', 'completed'])->default('pending');
    $table->enum('priority', ['low', 'medium', 'high'])->default('medium');
    $table->date('due_date')->nullable();
    $table->timestamps();
    $table->index(['status', 'priority']);
});

And the store method in the controller:

public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|string|max:255',
        'description' => 'nullable|string',
        'status' => 'required|in:pending,in-progress,completed',
        'priority' => 'required|in:low,medium,high',
        'due_date' => 'nullable|date|after_or_equal:today',
    ]);

    Task::create($validated);

    return redirect()->route('tasks.index')
        ->with('success', 'Task created successfully.');
}

Several things make this generated code solid. The validation rules mirror the database constraints — in:pending,in-progress,completed matches the enum values in the migration, so invalid data is rejected before it reaches the database. The after_or_equal:today rule on due_date prevents setting deadlines in the past. The nullable rules match the nullable columns in the migration, keeping the contract consistent between validation and storage.

The composite index on ['status', 'priority'] targets the most common query pattern: filtering tasks by status and sorting by priority. This is a detail many developers forget during initial scaffolding, but the AI includes it because the prompt specified filtering and sorting.

Flash messages via ->with('success', ...) give the user immediate feedback after creating a task. The Blade templates pick this up with a session check and display a styled notification bar.

Extending the Generated App

Once the base CRUD app is running, you can iterate with follow-up prompts. Each prompt builds on the existing codebase rather than regenerating from scratch.

Adding Relationships

Add a Category model with a many-to-many relationship to tasks.
Include a migration for the category_tasks pivot table.
Add a category filter dropdown to the task list page.

This generates a Category model, a pivot table migration, belongsToMany relationships on both models, and updated Blade views with a dropdown that filters tasks by category.

Adding Authentication

Add Laravel Breeze authentication and scope tasks to the logged-in user.
Only show tasks belonging to the authenticated user.
Add a user_id foreign key to the tasks migration.

The AI will install Breeze's scaffolding, add a user_id column with a foreign key constraint, set up the belongsTo/hasMany relationship between User and Task, and update controller methods to use auth()->user()->tasks() instead of Task::all().

Adding an API Layer

Add API routes with JSON responses and token authentication using Laravel Sanctum.
Include endpoints for listing, creating, updating, and deleting tasks.
Return proper HTTP status codes.

This generates an api.php route file with token-protected endpoints, a controller (or the same controller with conditional response formatting) that returns JSON, and proper status codes like 201 for creation and 204 for deletion.

Iterating

Once your base CRUD is running, you are not limited to the examples above. Here are more prompts that work well:

  • "Add a dashboard page showing task statistics with counts by status"
  • "Add search functionality to the task list using Eloquent where clauses"
  • "Add soft deletes with a trash view and restore functionality"
  • "Add CSV export for the task list using Laravel's streaming response"
  • "Add drag-and-drop reordering with a sort_order column"

Each of these prompts produces a targeted addition to the existing codebase. The AI understands the project context and adds new code that integrates with what is already there.

Best Practices the AI Follows

The generated Laravel code follows framework conventions:

  • Mass assignment protection via $fillable — Only explicitly listed attributes can be set through create() or update(), preventing unintended field injection.
  • Form request validation for input safety — All user input is validated before it touches the database, with rules that match the schema constraints.
  • Eloquent relationships when multiple models are involved — Proper hasMany, belongsTo, and belongsToMany definitions with foreign keys and pivot tables.
  • Blade component architecture for reusable UI pieces — Shared layouts, partial views, and component-based structure that keeps templates maintainable.
  • Route model binding for cleaner controller methods — Type-hinted model parameters that automatically resolve from route segments, eliminating manual findOrFail calls.
  • Flash messages for user feedback — Success and error messages passed through the session and displayed in the layout template.
  • CSRF protection — All forms include @csrf tokens, and destructive actions use @method('DELETE') or @method('PUT') as appropriate.
  • Old input repopulation — Form fields use old('field_name') so users do not lose their input when validation fails.

AI Model Comparison for Laravel

Not all AI models produce equally good Laravel code. Here is how the major models compare when generating Laravel CRUD applications:

| Model | Eloquent Quality | Blade Templates | Migration Accuracy | |-------|-----------------|-----------------|-------------------| | Claude 3.5 Sonnet | Excellent | Excellent | Excellent | | GPT-4o | Excellent | Great | Excellent | | Mistral Large | Great | Good | Great |

Claude 3.5 Sonnet consistently produces the most idiomatic Laravel code, with correct use of newer features like Eloquent casts as classes and Laravel 11 conventions. GPT-4o is strong across the board, particularly with complex validation rules and migration schemas. Mistral Large handles standard CRUD well but occasionally misses Blade-specific nuances like proper @error directive usage or component slot syntax. See the full AI models comparison for all supported providers.

For best results with any model, be explicit about the Laravel version you are targeting and the specific patterns you want (Blade components vs. traditional layouts, form requests vs. inline validation).

Common Issues and Solutions

Even with AI-generated code, a few issues come up regularly. Knowing about them ahead of time lets you address them in your prompt or fix them quickly.

Missing CSRF Tokens in Forms

If form submissions return a 419 Page Expired error, the generated Blade template is missing the @csrf directive inside the <form> tag. This is rare with modern models but can happen if the prompt asks for raw HTML forms instead of Blade templates. Fix it by adding @csrf as the first line inside every form, or mention "include CSRF protection in all forms" in your prompt.

N+1 Query Problems

If the task list page loads slowly as your data grows, the controller may be loading related models one at a time inside a loop. This is the classic N+1 problem. Tell the AI to use eager loading by adding "use eager loading for relationships" to your prompt. The AI will then generate queries like Task::with('category', 'user')->get() instead of lazy-loading related models inside Blade @foreach loops.

Validation Errors Not Displaying

If you submit an invalid form and get redirected back without seeing any error messages, the Blade template is likely missing the @error directive or the $errors variable check. Add "show validation errors next to each form field in Blade using the @error directive" to your prompt. This ensures the AI generates error display blocks like @error('title') <span class="text-red-500">{{ $message }}</span> @enderror beneath each input.

When to Use Laravel vs Other Templates

| Scenario | Recommended Template | |----------|---------------------| | Full-stack web app with database | Laravel | | API-only backend | PHP or Laravel | | Interactive frontend with API calls | React or Next.js | | Data dashboard | Streamlit | | Quick prototype without backend | React or Vue |

Laravel is the strongest choice when you need server-rendered HTML, database operations, and form handling in a single cohesive framework. Browse all framework templates or see how Laravel compares to PHP for backend projects. If your project is primarily a JSON API consumed by a separate frontend, Laravel still works but you may prefer a lighter setup depending on complexity.

FAQ

Q: Does the generated Laravel app use a real database?

Yes. LoomCode AI's Laravel sandbox includes SQLite by default. The AI generates proper migrations that run automatically when the sandbox starts. SQLite works well for development and prototyping. For production, you can switch to MySQL or PostgreSQL by updating the .env file and database configuration — the Eloquent code remains the same.

Q: Can I add packages via Composer?

The sandbox supports Composer. You can ask the AI to include specific packages like "add Laravel Breeze for authentication" or "use Spatie packages for media handling." The AI will add the dependency, publish configuration files, and integrate the package into the existing application code.

Q: How do I deploy a Laravel app generated with LoomCode AI?

Copy the generated code and deploy to any Laravel-compatible hosting: Laravel Forge, Railway, DigitalOcean, or shared hosting with PHP support. The code follows standard Laravel conventions so deployment is straightforward. Run composer install, set your .env variables, run php artisan migrate, and your application is ready to serve traffic.

Q: What if the generated code has a bug?

Describe the issue in a follow-up prompt. For example, "The task edit form does not preserve the current status value — fix the select dropdown to show the existing status as selected." The AI will locate the relevant Blade template and correct the issue, typically by adding a selected attribute check to the <option> elements.

Ready to build your app?

Describe your idea and get a working app in seconds with LoomCode AI.

Start Building