Seeding from a package / Fixing ReflectionException

- 1 answer

Ad

I have created a package which copies migrations and seeds to the respective directories in the base app.

However, unless I call (add) these within the run() function in the DatabaseSeeder class in the base app (app/database/seeds/DatabaseSeeder.php) when I run

php artisan migrate:refresh --seed

Then the seeds are not run. How can I automate this part so the user doesn't have to manually edit this file? Are there any artisan commands to manually run seeds?

Ad

Answer

Ad

Still don't completely understand how I got this to work, but for others;

In your boot method of your PackagenameServiceProvider use $this->publishes() to move the seeds and migrations to the base app

public function boot()
{
    if (!$this->app->routesAreCached()) {
        require __DIR__.'/../routes.php';
    }

    $this->publishes([
        __DIR__.'/../DatabaseStuff/Migrations' => $this->app->databasePath().'/migrations',
        __DIR__.'/../DatabaseStuff/Seeds/Example1Seeder.php' => $this->app->databasePath().'/seeds/Example1Seeder.php',
        __DIR__.'/../DatabaseStuff/Seeds/Example2Seeder.php' => $this->app->databasePath().'/seeds/Example2Seeder.php',
    ]);
}

Have a copy of DatabaseSeeder with call methods pointing to the seeds you wish to run but make sure it's name-spaced correctly to where ever you have the files in your package.

namespace ExampleVendor\ExamplePackage\DatabaseStuff;

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

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

        $this->call(\Example1Seeder::class);
        $this->call(\Example2Seeder::class);

        Model::reguard();
    }
}

Now run the following commands. The critical command for me in this case was php artisan optimize

php artisan vendor:publish

composer dump-autoload

php artisan cache:clear

php artisan optimize

php artisan db:seed --class="ExampleVendor\ExamplePackage\DatabaseStuff\DatabaseSeeder"

Without php artisan optimize I kept getting

ReflectionException                                         
Class ExampleVendor\ExamplePackage\DatabaseStuff\DatabaseSeeder does not exist

Hopefully this helps someone in the future.

Ad
source: stackoverflow.com
Ad