AI

/laravel-agent:bug:fix

AI-powered bug analysis and fix suggestions

Overview

The /bug:fix command provides intelligent error analysis for Laravel applications. It examines error messages, parses stack traces, identifies root causes, and suggests actionable fixes with multiple solution options. The AI analyzes your codebase context to provide tailored recommendations specific to your application architecture.

Usage

/laravel-agent:bug:fix [error-source]

Error Sources

You can provide errors from multiple sources:

  • Latest from logs - Automatically reads from storage/logs/laravel.log
  • Direct error message - Paste the error text directly
  • Specific log file - Provide path to any log file
  • Exception type - Search for specific exception classes
  • Telescope - Extract from Laravel Telescope exceptions

Examples

# Analyze latest error from logs
/laravel-agent:bug:fix

# Analyze specific error message
/laravel-agent:bug:fix "Class 'App\Services\PaymentService' not found"

# Analyze from specific log file
/laravel-agent:bug:fix storage/logs/laravel.log

# Find specific exception type
/laravel-agent:bug:fix --exception=QueryException

# Analyze validation errors
/laravel-agent:bug:fix "The email field is required"

Common Error Patterns

The command recognizes and provides specialized analysis for these common Laravel error patterns:

Error Type Common Causes Typical Solutions
QueryException Missing columns, foreign key constraints, duplicate entries, SQL syntax errors Add migrations, fix constraints, check unique indexes
Class Not Found Missing imports, autoload issues, namespace mismatches Add use statements, run composer dump-autoload, fix namespaces
Method Not Found Typos in method names, missing traits, wrong model relationships Fix method names, add traits, correct relationship definitions
Validation Errors Missing validation rules, custom rule issues, Request class problems Add rules, fix custom validators, update Form Requests
Authentication Issues Guard configuration, middleware order, session problems Configure guards, reorder middleware, check session driver

How Analysis Works

The bug analysis process follows these steps:

  1. Gather Error Context - Extracts error messages from logs, Telescope, or provided text
  2. Parse Stack Trace - Identifies the call chain leading to the error
  3. Identify Root Cause - Determines the underlying issue, not just the symptom
  4. Find Related Code - Locates relevant files and examines surrounding context
  5. Check Common Patterns - Matches against known Laravel error patterns
  6. Generate Solutions - Provides multiple fix options with code examples
  7. Suggest Prevention - Recommends tests and practices to avoid recurrence

Example Analysis Output

When analyzing a database error, you'll receive structured output like this:

## Bug Analysis: QueryException

### Error
```
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found:
1054 Unknown column 'users.tenant_id' in 'where clause'
```

### Root Cause
The `tenant_id` column is referenced in a query scope but doesn't exist
in the users table. This typically occurs when:
- A migration was not run
- The scope was added without a corresponding schema change
- A column was renamed but the scope wasn't updated

### Stack Trace
| # | File | Line | Method |
|---|------|------|--------|
| 1 | app/Models/User.php | 45 | scopeForTenant |
| 2 | app/Services/UserService.php | 23 | getUsers |
| 3 | app/Http/Controllers/UserController.php | 15 | index |

### Solution

**Recommended Fix: Add the missing column**

1. Create a migration:
```bash
php artisan make:migration add_tenant_id_to_users_table
```

2. Add the column:
```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->foreignId('tenant_id')->nullable()->after('id');
            $table->foreign('tenant_id')->references('id')->on('tenants');
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropForeign(['tenant_id']);
            $table->dropColumn('tenant_id');
        });
    }
};
```

3. Run the migration:
```bash
php artisan migrate
```

**Alternative Fix: Update the scope if column shouldn't exist**

If you're using a different column for tenant relationships:

```php
// app/Models/User.php

// Before
public function scopeForTenant($query, $tenantId)
{
    return $query->where('tenant_id', $tenantId);
}

// After (if using different column)
public function scopeForTenant($query, $tenantId)
{
    return $query->where('organization_id', $tenantId);
}
```

### Prevention
- Add a test for the tenant scope
- Run `php artisan migrate` before deploying to production
- Use CI/CD pipelines to catch missing migrations
- Consider adding a model test:

```php
test('users can be filtered by tenant', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create(['tenant_id' => $tenant->id]);

    $users = User::forTenant($tenant->id)->get();

    expect($users)->toContain($user);
});
```

### Files to Review
- app/Models/User.php (line 45)
- database/migrations/xxxx_add_tenant_id_to_users_table.php (create)
- tests/Unit/Models/UserTest.php (add test)

Interactive Mode

When run without arguments, the command enters interactive mode and prompts you for:

  1. Error source - Choose from latest logs, paste error, specify file, or use Telescope
  2. Error type - Categorize as database, class/method, validation, authentication, or other
  3. Apply fix automatically - Option to create migrations or edit files directly

Example Scenarios

Scenario 1: Missing Class Import

/laravel-agent:bug:fix "Class 'Carbon' not found"

Analysis Output:

### Root Cause
Carbon class is used without importing it at the top of the file.

### Solution
Add the import statement:
```php
use Carbon\Carbon;
```

Or use the global namespace:
```php
\Carbon\Carbon::now()
```

Scenario 2: Foreign Key Constraint

/laravel-agent:bug:fix --exception=QueryException

Analysis Output:

### Root Cause
Attempting to delete a parent record that has dependent child records.

### Solution
Either:
1. Delete child records first
2. Add `onDelete('cascade')` to the foreign key
3. Set foreign key to `onDelete('set null')` and make column nullable

Scenario 3: Method Not Found

/laravel-agent:bug:fix "Call to undefined method getFullNameAttribute"

Analysis Output:

### Root Cause
Accessor method name doesn't follow Laravel naming convention.

### Solution
Change from:
```php
public function getFullNameAttribute()
```

To (for Laravel 9+):
```php
use Illuminate\Database\Eloquent\Casts\Attribute;

protected function fullName(): Attribute
{
    return Attribute::make(
        get: fn () => "{$this->first_name} {$this->last_name}"
    );
}
```

Best Practices

  1. Preserve stack traces - Include full error output for better analysis
  2. Review before applying - Understand the suggested fix before accepting automatic changes
  3. Add tests - Implement the prevention tests suggested in the analysis
  4. Check multiple environments - Verify fixes work in development, staging, and production
  5. Update documentation - Document non-obvious fixes for your team
  6. Use version control - Commit working state before applying fixes

Tips for Better Analysis

  • Include the full error message with file paths and line numbers
  • Provide context about what you were trying to do when the error occurred
  • Mention any recent changes that might be related
  • Specify your Laravel version for version-specific solutions
  • Include relevant configuration (database, queue, cache drivers)

See Also