Giter Site home page Giter Site logo

laravel-automatic-migrations's People

Contributors

bastinald avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

laravel-automatic-migrations's Issues

Laravel 9?

Will you be updating this for Laravel 9?

Suggest: Confirm migration if is about to delete columns

This issue is only a proposal:

Since auto migration could lead to accidental column deletions and data loss while updating existing tables, I added some code to MigrateAutoCommand.php to alert the user if the running migration is about to delete some columns.

Here is my proposal:

     [ ... ]
           $tableDiff = (new Comparator)->diffTable($modelTableDetails, $tempTableDetails);

            if ($tableDiff) {
                $delcount=count($tableDiff->removedColumns);    
                if ($delcount==0 || 
                     $this->confirm('This migration will delete ' . $delcount . ' column(s): ['  . 
                           implode(', ',array_keys($tableDiff->removedColumns))  .   ']. Proceed?')){

                    $schemaManager->alterTable($tableDiff);

                    $this->line('<info>Table updated:</info> ' . $modelTable);
                }
                else {
                    $this->line('<info>Table update CANCELED:</info> ' . $modelTable);
                }
            }
     [ ... ]

Bye,
Marco

Pivot Tables

Should i just create vanilla laravel migration tables for pivot tables or is there a way to handle it with this library? Lets say I have a Post model and a Category model and I want to be able to associate multiple Categories to a Post (belongsToMany).

Users Table getting duplicated after initial migrate:auto

Hello,

Whenever I run the migrate:auto command after the initial users table has been created, the command creates a new table called "table_users". I have a video demonstrating the issue happening on a fresh laravel project, (you can skip through to around 01:28 as it takes it's sweet time to create a new project on windows!): Video Link. It has the following error:


  SQLSTATE[42P07]: Duplicate table: 7 ERROR:  relation "table_users_email_unique" already exists (SQL: alter table "table_users" add constraint "table_users_email_unique" unique ("email"))

  at C:\Devspace\lam_error_test\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
    688▕         // If an exception occurs when attempting to run a query, we'll format the error
    689▕         // message to include the bindings with SQL, which will make this exception a
    690▕         // lot more helpful to the developer instead of just the database's errors.
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕     }

  1   C:\Devspace\lam_error_test\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485
      PDOException::("SQLSTATE[42P07]: Duplicate table: 7 ERROR:  relation "table_users_email_unique" already exists")

  2   C:\Devspace\lam_error_test\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485
      PDOStatement::execute()

Duplicate Forign Key Constraint Name issue

Heya, just started out a fresh project using your livewire-ui package, however i am encountering an issue with the automatic migrations. It doesnt seem to be handling a foreign key constraint properly when checking for differences in the table. I can migrate initially, however even with no changes, i run the migrate:auto command and it seems to try to re-add the foreignId as i get an error that the constraint already exists. Not sure if im just missing something obvious or if this is a bug!

Video of issue

Using Sail Docker dev environment using MySQL 8.0.

Cheers!

Artisan::call

Hi!

If I modify LaravelAutomaticMigrationsProvider class like this:
...
if ($this->app->runningInConsole()) {
$this->commands([
MakeAModelCommand::class,
]);
}

    $this->commands([
            MigrateAutoCommand::class,
        ]);

...

It help to migrate an exist database where I can't run OS command.

I can use Artisan::call command browser
Route::get('/migrate', function() {
Artisan::call('migrate:auto');
return "Your database migrated";
});

I use this doc: https://nono.ma/laravel-artisan-the-command-does-not-exist

Nándi

Extract paths to constant or variables

[__DIR__ . '/../../config/laravel-automatic-migrations.php' => config_path('laravel-automatic-migrations.php')],

First hi, I want to say that is very interesting project.
Here on publish I see that multiple times are used same paths:

'/../../config'
'/../../resources'

As a purpose maybe will be better to extract them to variables or constants(if will be used on other classes), as example:

$configPath = __DIR__ . '/../../config';
$resourcesPath = __DIR__ . '/../../resources';

or in class

const CONFIG_PATH = __DIR__ . '/../../config';
const RESOURCES_PATH = __DIR__ . '/../../resources';

and usage will be

 $this->publishes(
            ["{$configPath}/laravel-automatic-migrations.php" => config_path('laravel-automatic-migrations.php')],
 ...

or

 $this->publishes(
            [CONFIG_PATH  . '/laravel-automatic-migrations.php' => config_path('laravel-automatic-migrations.php')],
 ...

Relations when it comes to seeds

One thing i am struggling to figure out how to do relations with the seed data in the definition(). Not sure how i can make that 'contact_id' in the seed related to an actual contact from the Contact model. Will be useful to know for other uses. Right now i just have a hard contact id set of 1.

<?php

namespace App\Models;

use Bastinald\UI\Traits\HasFillable;
use Faker\Generator;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Schema\Blueprint;

class Transaction extends Model
{
    use HasFactory;
    use HasFillable;
    use SoftDeletes;

    public function migration(Blueprint $table)
    {
        $table->id();
        $table->unsignedBigInteger('contact_id');
        $table->string('description');
        $table->string('payment_gateway');
        $table->string('gateway_transaction_id');
        // create unique relationship
        $table->unique(['payment_gateway', 'gateway_transaction_id']);
        $table->decimal('amount', 10, 2);
        $table->decimal('fees', 10, 2)->default(0.00);
        $table->timestamp('created_at')->nullable();
        $table->timestamp('updated_at')->nullable();
        $table->softDeletes();
    }

    public function definition(Generator $faker)
    {
        return [
            'contact_id' => 1,
            'description' => $faker->words,
            'payment_gateway' => 'square',
            'gateway_transaction_id' => $faker->unique()->numerify('########'),
            'amount' => $faker->randomFloat(2, 10, 20),
            'fees' => $faker->randomFloat(2, 0, 0.4),
        ];
    }
}

Migration order by date as attribute

It would be nice and more aligned with how the [Migration Order](../tree/master/readme.md#Migration Order) natively works in Laravel, to have an Attribute automatically created, containing the date of the migration creation:

Note

Each migration filename contains a timestamp that allows Laravel to determine the order of the migrations

use Bastinald\LaravelAutomaticMigrations\Attributes\MigrationScaffoldedAt;

class MyModel extends Model
{
    #[MigrationScaffoldedAt('2024_01_10_123456')]
    public function migration(Blueprint $table)
    {
        $table->id();
        $table->string('name');
        $table->timestamp('created_at')->nullable();
        $table->timestamp('updated_at')->nullable();
    }
}

This would then be implemented something like this:

<?php

namespace Bastinald\LaravelAutomaticMigrations\Commands;

[…]
use Bastinald\LaravelAutomaticMigrations\Attributes\MigrationScaffoldedAt;
use ReflectionClass;

class MigrateAutoCommand extends Command
{
    […]

    private function handleAutomaticMigrations()
    {
        […]

        foreach ((new Finder)->in($path) as $model) {
            […]

            if (method_exists($model, 'migration')) {
                $object = app($model);
                $reflection = new ReflectionClass($model);
                $attribute  = $reflection->getAttributes(MigrationScaffoldedAt::class)[0];
                $scaffoldingDate = $attribute->getArguments()[0];

                $models->push([
                    'object' => $object,
                    'order' => $object->migrationOrder ?? $scaffoldingDate ?? 0
                ]);
            }
        }

        foreach ($models->sortBy('order') as $model) {
            $this->migrate($model['object']);
        }
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.