Automatic Laravel model migrations.

Overview

Laravel Automatic Migrations

Automatic Laravel model migrations. Instead of having to create and manage migration files, this package allows you to specify your migrations inside your model classes via a migration method. When you run the migrate:auto command, it uses Doctrine to compare your model migration methods to the existing schema, and applies the changes automatically.

This package works perfectly fine alongside traditional Laravel migration files, for the edge cases where you still need migrations that are not coupled to a model. When you run the migrate:auto command, it will run your traditional migrations first, and the automatic migrations afterwards.

Documentation

Installation

Require the package via composer:

composer require bastinald/laravel-automatic-migrations

Usage

Declare a migration method in your models:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Eloquent\Model;

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

Run the migrate:auto command:

php artisan migrate:auto

Commands

Making Models

Make a model with a migration method included:

php artisan make:amodel {name}

Making Factories

Make a factory whose definition points to a model:

php artisan make:afactory {name}

Running Migrations

Run automatic migrations:

php artisan migrate:auto {--f|--fresh} {--s|--seed} {--force}

Publishing Stubs

Use your own model and factory stubs by publishing package files:

php artisan vendor:publish --tag=laravel-automatic-migrations

Update the stub_path in config/laravel-automatic-migrations.php:

'stub_path' => base_path('resources/stubs/vendor/laravel-automatic-migrations'),

Now just edit the stub files inside resources/stubs/vendor/laravel-automatic-migrations to your needs. The commands will now use these stub files to make models and factories.

Traits

HasHashes

This trait will automatically hash attributes specified via a $hashes property in your model. It will only do so if the values are not already hashed, so it does not slow down seeders.

use Bastinald\LaravelAutomaticMigrations\Traits\HasHashes;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasHashes;

    protected $hashes = ['password'];
}
Comments
  • Users Table getting duplicated after initial migrate:auto

    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()
    
    opened by AlexJames-Dev 4
  • Add migration sequence to accomodate ->constrained() migration

    Add migration sequence to accomodate ->constrained() migration

    Hello @bastinald,

    Thanks a lot for this awesome package. I'm Vincent from Indonesia, I recently explored your laravel-livewire-ui package. However I found a problem whenever I create migration for a table that has a foreign to other tables. An error would occurred because the migration of related table run before the foreign table exist:

    SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `table_products` add constraint `table_products_category_id_foreign` foreign key (`category_id`) references `id` (`categories`))
    

    I tried to make some modification by sorting the model files using defined $migration_sequence variable. Using this variable, we can defined the migration running sequence.

    If you think this is a good solution, you can freely accept this PR.

    Thanks.

    opened by vincentkedison 3
  • Relations when it comes to seeds

    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),
            ];
        }
    }
    
    opened by MACscr 2
  • Extract paths to constant or variables

    Extract paths to constant or variables

    https://github.com/bastinald/laravel-automatic-migrations/blob/31d26e9ab35e41d25692524fd32b8ff92f7959fc/src/Providers/LaravelAutomaticMigrationsProvider.php#L23

    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')],
     ...
    
    opened by codebjorn 1
  • Provide ways to define Model directory

    Provide ways to define Model directory

    I am developing my application using https://nwidart.com/laravel-modules and there is no way to auto-discover the models generated in the Modules folder.

    Kindly provide way of specify preferred models files path,

    opened by dedanirungu 1
  • package has moved

    package has moved

    this package has moved here: https://github.com/legodion/lucid

    i am the author, this is my alt account

    that repo will be updated and maintained going forward. it supports Laravel 9 etc.

    opened by legodion 0
  • Suggest: Confirm migration if is about to delete columns

    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

    opened by marstell-sw 0
  • Pivot Tables

    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).

    opened by MACscr 2
  • Artisan::call

    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

    opened by NandorArgyelan 0
Releases(3.0.1)
Owner
null
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

null 66 Sep 19, 2022
A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Touhidur Rahman 13 Jan 20, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022
Laravel-model-mapper - Map your model attributes to class properties with ease.

Laravel Model-Property Mapper This package provides functionality to map your model attributes to local class properties with the same names. The pack

Michael Rubel 15 Oct 29, 2022
Automatic multi-tenancy for Laravel. No code changes needed.

Tenancy for Laravel — stancl/tenancy Automatic multi-tenancy for your Laravel app. You won't have to change a thing in your application's code. ✔️ No

Samuel Štancl 2.7k Jan 3, 2023
Laravel Helpers Automatic Loading System

About Laravel Helpers Automatic Load Laravel Helpers Automatic Loading System Doc: Copy the Helpers folder and paste it on app folder Then Go To app/P

IQBAL HASAN 2 Nov 9, 2021
Automatic human timestamps for Laravel Eloquent models.

Automatic human timestamp properties in Laravel This package provides a trait you can add to an Eloquent model that will automatically create human-re

Christopher Di Carlo 25 Jul 17, 2022
Declare database migrations and factory definitions inside Laravel models.

Lucid This package allows you to declare database migrations and factory definitions inside of your Laravel models. Running the lucid:migrate command

null 23 Jul 9, 2022
Easily add all the 58 Algerian Wilayas and its Dairas to your cool Laravel project (Migrations, Seeders and Models).

Laravel-Algereography Laravel-Algereography allows you to add Migrations, Seeders and Models of Algerian Wilayas and Dairas to your existing or new co

Hocine Saad 48 Nov 25, 2022
Laravel MiGator - Migrations Generator

Laravel Migator A package that will allow developers to interactively generate schema migrations for a laravel application. It takes into account the

Synetic 2 Oct 13, 2022
Validate PHP database migration files for compliance with best practices. Ensure db migrations are irreversible.

PHP DB Migration Validator Introduction In modern PHP frameworks such as Symfony and Laravel, migrations usually have up and down methods. In up metho

Anton Komarev 17 Dec 14, 2022
This package extends Illuminate to provide partitioned table creation in migrations.

Laravel Partitions for Migrations This package extends Illuminate to provide partitioned table creation in migrations for PostgreSQL. Support for othe

ORPTech 9 Oct 24, 2022
A Laravel package that adds a simple image functionality to any Laravel model

Laraimage A Laravel package that adds a simple image functionality to any Laravel model Introduction Laraimage served four use cases when using images

Hussein Feras 52 Jul 17, 2022
Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Rubik 4 May 12, 2022
This Laravel package merges staudenmeir/eloquent-param-limit-fix and staudenmeir/laravel-adjacency-list to allow them being used in the same model.

This Laravel package merges staudenmeir/eloquent-param-limit-fix and staudenmeir/laravel-adjacency-list to allow them being used in the same model.

Jonas Staudenmeir 5 Jan 6, 2023
Easily create a revision history for any laravel model

Wouldn't it be nice to have a revision history for any model in your project, without having to do any work for it. By simply adding the RevisionableT

Venture Craft 2.4k Jan 6, 2023
laravel-model-validator

laravel-model-validator This is a simple validator. The validator can be created by command. The validator has all common table column constraint, eg:

null 6 May 22, 2022
Update multiple Laravel Model records, each with it's own set of values, sending a single query to your database!

Laravel Mass Update Update multiple Laravel Model records, each with its own set of values, sending a single query to your database! Installation You

Jorge González 88 Dec 31, 2022
Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

Egor Shitikov 87 Nov 26, 2022