Check if migration exists in Laravel package service provider

639 Views Asked by At

I'm writing a Laravel package, in its service provider, the package receives a list of migrations to publish, using the code below:

protected function publishMigrations(array $publishables): void
{
    // Generate a list of migrations that have not been published yet.
    $migrations = [];
    foreach($publishables as $publishable)
    {
        // Migration already exists, continuing
        if(class_exists($publishable)){
            continue;
        }
        $file = Str::snake($publishable) . '.php';
        $migrations[self::MIGRATIONS_PATH . $file . '.stub'] = database_path('migrations/'.date('Y_m_d_His', time())."_$file");
    }

    $this->publishes($migrations, 'migrations');
}

An example of the package's $publishables would be:

$publishables = ['CreateAuthenticationsTable', 'CreateCustomersTable', 'CreateTransactionsTable'];

The code does work as expected, publishing the migrations I'm intending to publish, however, I'm trying to avoid publishing the same migration twice using the class_exists($publishable) line. As I understood, the same approach is being used by Laravel MediaLibrary. But I'm guessing the migrations aren't loaded when publishing assets because that piece of code doesn't ever run. (class_exists is false all the time)

Is there a way I can keep track of the already published migrations? is this an auto-load issue?

1

There are 1 best solutions below

1
On

This migrationExists($mgr) function will check if a migration file exists in database/migrations. It will loop over migration file names and check for a name match for given migration name.

protected function publishMigrations()
    {
        if (!$this->migrationExists('create_admins_table')) {
            $this->publishes([
              __DIR__ . '/database/migrations/create_admins_table.php.stub' => database_path('migrations/' . date('Y_m_d_His', time()) . '_create_admins_table.php'),
              // you can add any number of migrations here
            ], 'migrations');
            return;
        }
    }



protected function migrationExists($mgr)
    {
        $path = database_path('migrations/');
        $files = scandir($path);
        $pos = false;
        foreach ($files as &$value) {
            $pos = strpos($value, $mgr);
            if($pos !== false) return true;
        }
        return false;
    }