# AI in a Laravel Project: From Migrations to Safe Refactoring

- آدرس: https://di9.ir/blog/en/ai-laravel-project-migrations-refactoring
- نویسنده: danidiba
- انتشار: 2026-09-25T18:12:00+03:30
- به‌روزرسانی: 2026-09-25T18:12:00+03:30
- دسته: AI-Assisted Coding
- برچسب‌ها: Eloquent، بازآرایی کد، لاراول، مایگریشن، هوش مصنوعی

> AI models know Laravel well, but they mix old and new project structures. This guide shows what context to provide so the code matches your version, how to review migrations and Eloquent queries, and how to refactor in small, safe steps.

Laravel is one of the frameworks AI knows best: tidy documentation, a large community and plenty of sample code. As a result, generated code is usually clean and familiar.

The problem lies elsewhere: the model has seen every Laravel version at once and sometimes mixes the structure of a few years ago with today's. This article is about getting code that fits your own project, from migrations to refactoring.

## What context should you give the AI?

The exact Laravel and PHP versions, the runtime environment, and the real files related to the task; not the whole project.

Two commands give most of the information you need:

```bash
php artisan about
composer show laravel/framework
```

The first command shows the Laravel and PHP versions, the environment, the cache and queue drivers and more. Read the output and remove any sensitive value before sending it. Mention the runtime environment too: code that works on a VPS may hit [disabled PHP functions](https://di9.ir/blog/disable-functions-%D9%87%D8%A7%D8%B3%D8%AA-%D8%A7%D8%B4%D8%AA%D8%B1%D8%A7%DA%A9%DB%8C) on shared hosting. We covered the limits of that kind of hosting in the [shared hosting checklist for Laravel](https://di9.ir/blog/%DA%86%DA%A9-%D9%84%DB%8C%D8%B3%D8%AA-%D9%87%D8%A7%D8%B3%D8%AA-%D8%A7%D8%B4%D8%AA%D8%B1%D8%A7%DA%A9%DB%8C-%D8%A8%D8%B1%D8%A7%DB%8C-%D9%84%D8%A7%D8%B1%D8%A7%D9%88%D9%84).

A common example of version mixing: in the newer Laravel structure there is no `app/Http/Kernel.php`, and middleware is registered in `bootstrap/app.php`. A model that does not know your version may still say "add this to the Kernel". The simple fix: attach a real file from the project, such as that same `bootstrap/app.php`, so the model can see the structure.

## How do you review migrations written by AI?

Generate the migration quickly, but before running it check the `down` method, the indexes and the effect on existing rows.

Suppose you want to add a shipment tracking code to the orders table and speed up each user's order report:

```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(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->string('tracking_code', 64)->nullable()->after('status');
            $table->index(['user_id', 'created_at']);
        });
    }

    public function down(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->dropIndex(['user_id', 'created_at']);
            $table->dropColumn('tracking_code');
        });
    }
};
```

Before running it, go through this checklist:

| Check | Why |
| --- | --- |
| Does the new column on a populated table have `nullable` or a default value? | Otherwise existing rows have no value and the migration fails |
| Is `down` the exact reverse of `up`? | Models sometimes leave `down` empty or incomplete |
| Is the index on columns that queries really filter by? | An unused index slows down writes |
| Does the string index length fit your MySQL version? | Key length errors are common on older MySQL versions |
| Is the table large? | Changing the structure of a large table may lock it for a while |

Then look at the final SQL without running it:

```bash
php artisan migrate --pretend
```

On the production server, run it only after a full database backup. If you get an error, see how to report it to the AI in [debugging with AI](https://di9.ir/blog/%D8%AF%DB%8C%D8%A8%D8%A7%DA%AF-%D8%A8%D8%A7-%D9%87%D9%88%D8%B4-%D9%85%D8%B5%D9%86%D9%88%D8%B9%DB%8C).

## How does AI help with Eloquent queries?

Its biggest help is finding redundant queries, especially the N+1 problem, and suggesting eager loading.

The **N+1 problem** means that to display a list, one query runs for the list itself and a separate query runs for each row:

```php
// 51 queries: one for the orders and one for each order's customer
$orders = Order::latest()->take(50)->get();

foreach ($orders as $order) {
    echo $order->customer->name;
}

// 2 queries in total
$orders = Order::with('customer')->latest()->take(50)->get();
```

AI finds this pattern well in a controller or a Blade template, as long as it can see both. To make Laravel itself warn you in development, put this line in the `boot` method of `AppServiceProvider`:

```php
use Illuminate\Database\Eloquent\Model;

Model::preventLazyLoading(! $this->app->isProduction());
```

To count the real queries on each page, tools such as Laravel Debugbar or Telescope are more accurate than the model's guess.

## How do you refactor safely?

**Refactoring** means changing the structure of code without changing its behavior. To stay safe: tests first, then a plan, then small steps, one commit per step.

Suppose the `store` method in `OrderController` has grown to two hundred lines and handles order creation, stock deduction, payment and email all together.

1. **Write tests first** that cover the current behavior. Without tests you cannot tell whether the refactor broke something. The method is described in [writing automated tests with AI](https://di9.ir/blog/%D9%86%D9%88%D8%B4%D8%AA%D9%86-%D8%AA%D8%B3%D8%AA-%D8%A8%D8%A7-%D9%87%D9%88%D8%B4-%D9%85%D8%B5%D9%86%D9%88%D8%B9%DB%8C).
2. **Ask for a plan, not code.**
3. **Run each step separately**, read its diff the way [AI code review](https://di9.ir/blog/%D8%A8%D8%A7%D8%B2%D8%A8%DB%8C%D9%86%DB%8C-%DA%A9%D8%AF-%D8%A8%D8%A7-%D9%87%D9%88%D8%B4-%D9%85%D8%B5%D9%86%D9%88%D8%B9%DB%8C) describes, and then run the tests.
4. **Commit every green step** so you have a way back if the next step breaks.

```prompt
A Laravel project on PHP 8.3. I attached the store method of OrderController.
I want to move the order creation logic into a separate Action class.

Do not write code yet. Give me a refactoring plan in small steps, so that
the application works after each step. The external behavior, routes and
database structure must not change.
```

## Where should you be extra careful?

The model makes the most mistakes where it knows nothing about your version, packages or environment.

- **A package that does not exist or is abandoned:** before `composer require`, find the package on Packagist and check the date of its last update.
- **A made-up method:** if you do not recognize a method, search for it in the official Laravel documentation.
- **Queues and scheduling on shared hosting:** the model usually assumes you can run a permanent process.
- **Changes to configuration files:** review changes to `config` or `.env` separately; their effect is felt across the whole application.

## Where is AI in Laravel heading?

The direction is clear: tools get more access to the real structure of the project, such as routes, models and the database schema, and rely less on their general memory. Multi-file work, from migrations to tests, is also increasingly handed to agents.

To get ready, keep your project readable: write coding rules and folder structure in a short guide file at the project root, keep tests fast and reliable, and update Laravel regularly so the gap between your code and what models know best does not grow. The clearer the project is to a new teammate, the clearer it is to AI too.

## Summary

- Give the Laravel and PHP versions, the runtime environment and one real file from the project with your request.
- In migrations, check `down`, nullable columns, indexes and table size, and run `--pretend` first.
- Fix the N+1 problem with `with` and turn on `preventLazyLoading` in development.
- Refactor only behind tests, with a plan beforehand and small committed steps.
- Look up an unfamiliar package or method in the official source before using it.

## پرسش‌های متداول

### Which AI is best for Laravel programming?

All the major assistants know Laravel well, and their differences shift with every new release. What matters more than the model is the context you give: your Laravel and PHP versions, your composer.json and the related code. Give a real task from your own project to a few tools and compare the results.

### The AI suggests outdated Laravel code. What should I do?

Put the exact Laravel and PHP versions at the start of your request and attach a real file from the project, such as bootstrap/app.php or a controller, as a structure example. If outdated code still appears, ask the model which version the approach is valid for and check it against the official documentation.

### Can I run an AI-written migration directly on the server?

No. Run it on a local or staging environment first, test the down method too, and use the --pretend option to see the final SQL. On the production server, run it only after a full database backup, especially if the table is large or a column is changing.

### How do I introduce a Laravel project to an AI?

The output of php artisan about, the require section of composer.json, the models and migrations related to the task, and one sample of the project's coding style are enough. Do not send the whole project, and never give the .env file to a tool. If you work with an agent, put this information in a short guide file at the project root.
