jeudi 29 décembre 2016

Laravel/Composer: adding seeds programmatically

Currently I'm trying to develope a package update system with the following workflow. I'm creating a package (.zip) with the following files:

  • migrations (folder)
    • migrationClass
    • ..
  • seeds
    • seedfile
    • ..
  • package.xml
  • UpdateInstructionSeeder.php

As a administrator I can upload this package in my admin control panel to update my database.

backend workflow:

  1. get data from package.xml (get available seeds and migrations)
  2. check if a migration/seeding is needed
  3. migrate (works fine)
  4. seed (fails)

So, as you can see I have some trouble with my seeding.

At first I tried to move (with Storage::move()) my seeds from the package seed folder to the database/seed/ directory. I tried to seed it with Artisan::call('db:seed','--class']); but a Class MyClass does not exist error appeared. I guessed that there are some problems with my autoloader, so I've tried to dump it with system('composer dump-autoload', $test);. The output of $test was 1 but the autoload_classmap wasn't updated.

Now I've added a UpdateInstructionSeeder.php which is available in my framework by default to fix the autoloader problem. After uploading my package, I'm using now Storage::get() and Storage::put() to update this with my needed seeds.

Now I'm adding seeds with Artisan::call('make:seeder', ['name' => $className]); ($className is the name of my seeds from the package) and update them with Storage::get() and Storage::put(), too.

Now I'm calling my seeder with Artisan::call('db:seed','--class' => ']);. Result: Class MyClass does not exist

Content:

package UpdateInstructionSeeder

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class UpdateInstructionSeeder extends Seeder
{
   /**
    * Run the database seeds.
    *
    * @return void
    */
   public function run()
   {
       Model::unguard();

       $this->call(DemoTableSeeder::class);

       Model::reguard();
   }
}

package DemoTableSeeder

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DemoTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        DB::table('demos')->insert([
            [
                'demoInt' => 1,
                'demoString' => "a"
            ],
            [
                'demoInt' => 11,
                'demoString' => "aa"
            ],
        ]);

        Model::reguard();
    }
}

I wasted now a lot of hours and I have absolutely no idea to solve this problem programatically.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire