Search code examples
laravelcontrollermigrationlaravel-8database-migration

Is there a way to create dynamic migrations in Laravel?


I want to create the migrations file in dynamic. I developed a product management system and there are multiple stores in the system. I want to create product tables for the store when registering the store. my table names should like

  • store1_products
  • store2_products
  • store3_products table structure are same want to create these migration files in store create function

I all ready tried schema function on controller .

    Schema::create($tableName, function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token');
            $table->timestamps();
        });

It created the table on the database but I want to create the migration file too


Solution

  • I suggest to just create a one table for the store and one table for the product. Then the product table must have a column that identify what store it is belongs to.

    Stores Table.

    Schema::create('stores', function(Blueprint $table) {
        $table->id();
        $table->string('store_name');
        $table->timestamps();
    });
    
    

    Products Table

    Schema::create('products', function(Blueprint $table) {
        $table->id();
        $table->string('product_name')->unique();
        $table->unsignedFloat('price');
        $table->unsignedTinyInteger('quantity');
    
        $table->foreignId('store_id')
            ->constrained('stores')
            ->cascadeOnDelete();
    
        $table->timestamps();
    });
    
    

    Then you can refer to Laravel Eloquent Relationship to know how to define their relationship.

    Just make sure that you have model for them