Auto Generate Migration files and Models from Existing DB in Laravel

Auto Generate Migration Files

To automatically generate migration files from an existing database using “kitloong”

To automatically generate migration files from an existing database using the “kitloong/laravel-migrations-generator” package in Laravel, you can follow these steps:

1). Install the package via Composer:

composer require kitloong/laravel-migrations-generator

2). After installation, open the config/app.php file and add the following line to the providers array:

KitLoong\MigrationsGenerator\MigrationsGeneratorServiceProvider::class,

3). Publish the package’s configuration file by running the following command:

php artisan vendor:publish --provider="KitLoong\MigrationsGenerator\MigrationsGeneratorServiceProvider" --tag="migrations-generator-config"

4). Next, you need to configure the database connection details in the config/migrations-generator.php file. Modify the values according to your database configuration.

5). Finally, to generate the migration files, run the following command:

php artisan migrate:generate

The package will analyze your existing database structure and generate migration files for each table. The migration files will be placed in the database/migrations directory.

Note: Before running the migration generation command, ensure that your database connection is properly configured in Laravel’s ‘.env’ file.

Auto Generate Models

If you want to automatically generate models for all tables in your database without specifying each table individually, you can achieve this by writing a custom script. Here’s an example of how you can accomplish it

1). Create a new artisan command to generate models for all tables. Run the following command to generate the command file:

php artisan make:command GenerateModels

This will create a new file GenerateModels.php inside the app/Console/Commands directory.

2.) Open the generated file GenerateModels.php and update the handle method as follows:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class GenerateModels extends Command
{
    protected $signature = 'generate:models';

    protected $description = 'Generate models for all tables in the database';

    public function handle()
    {
        $tables = DB::connection()->getDoctrineSchemaManager()->listTableNames();

        foreach ($tables as $table) {
            $model = Str::studly(Str::singular($table));

            // Generate the model file
            $this->call('make:model', ['name' => $model]);

            $this->SetFillablePlaceholder($model);

            // Add fillable fields to the model
            $this->addFillableToModel($model, $table);
        }

        $this->info('Models generated successfully!');
    }

    protected function SetFillablePlaceholder($model)
    {
        usleep(50000); // Add a delay of 50 milliseconds to allow file creation

        $file = app_path("Models\\" . $model . ".php"); // Replace with the path to your PHP file
        $customText = "\t// FILLABLE_FIELDS";

        $fileLines = file($file);

        foreach ($fileLines as $index => $line) {
            if (strpos($line, 'use HasFactory;') !== false) {
                $insertIndex = $index + 1; // Insert after the specific line
                array_splice($fileLines, $insertIndex, 0, $customText);
                break;
            }
        }

        $fileContent = implode('', $fileLines);
        file_put_contents($file, $fileContent);
    }

    protected function addFillableToModel($model, $table)
    {
        usleep(50000); // Add a delay of 50 milliseconds to allow file creation

        $modelPath = app_path("Models\\" . $model . ".php");
        $fillableFields = $this->getFillableFields($table);

        // Check if the model file exists
        if (!file_exists($modelPath)) {
            $this->error("Model file does not exist at path {$modelPath}.");
            return;
        }

        $content = file_get_contents($modelPath);

        $fillable = "protected \$fillable = [\n";
        foreach ($fillableFields as $field) {
            $fillable .= "        '{$field}',\n";
        }
        $fillable .= "    ];\n";

        // Find the placeholder text and replace it with the fillable fields
    $placeholder = '// FILLABLE_FIELDS';
    if (strpos($content, $placeholder) !== false) {
        $content = str_replace($placeholder, $fillable, $content);
    } else {
        $content = str_replace('protected $fillable = [];', $fillable, $content);
    }

    file_put_contents($modelPath, $content);
    }

    protected function getFillableFields($table)
    {
        $columns = DB::connection()->getDoctrineSchemaManager()->listTableColumns($table);

        $fillableFields = [];
        foreach ($columns as $column) {
            if (!$column->getAutoincrement()) {
                $fillableFields[] = $column->getName();
            }
        }

        return $fillableFields;
    }
}


?>

3). Save the file, and now you can run the generate:models command to generate models for all tables in your database. Execute the following command:

php artisan generate:models

This command will iterate through all the tables in your database and generate a model for each table. The model name will be based on the table name.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *