I have a Symfony 4 application and Doctrine with Doctrine migrations. I'm introducing Codeception for running API tests, and need to run migrations before the tests run. Since I'm using the Doctrine2 module I don't really want to be also including the DB module as it's not needed for the tests and would require configuring the test database in two different locations.
I am using the Symfony module currently, and I noticed that the Laravel module has a run_database_migrations configuration option.
What is the best way to handle running the Doctrine migrations command in a Symfony app prior to the tests? (bin/console doctrine:migrations:migrate -n is the specific command).
Edit I've got a solution that, although it works, is nowhere near ideal. By using Codeception Customisation I've created the following extension that basically manually execs the underlying Symfony commands.
class DatabaseMigrationExtension extends Extension
{
public static $events = [
Events::SUITE_BEFORE => 'beforeSuite',
];
public function beforeSuite(SuiteEvent $e)
{
echo(exec('bin/console doctrine:database:drop --force') . PHP_EOL);
echo(exec('bin/console doctrine:database:create') . PHP_EOL);
echo(exec('bin/console doctrine:migrations:migrate -n') . PHP_EOL);
}
}
Edit 2 The goal of this is basically to replicate similar functionality to what the Codeception DB module does, which allows you to provide an SQL dump of a database that it automatically uses in the tests, but instead use Doctrine migrations to handle the DB. - https://codeception.com/docs/modules/Db#sql-data-dump
I spent a while trying a couple of different ways to achieve this. I initially used RunProcess however this seemed to cause sporadic issues with the DB being deleted and not recreated, despite using the sleep configuration. I ended up just updating the existing extension to use the CLI module instead, and it works as desired (without having to create scripts or run multiple commands) and without having to use exec.
Final extension;
class DatabaseMigrationExtension extends Extension
{
public static $events = [
Events::SUITE_BEFORE => 'beforeSuite',
];
public function beforeSuite()
{
try {
/** #var \Codeception\Module\Cli $cli */
$cli = $this->getModule('Cli');
$this->writeln('Recreating the DB...');
$cli->runShellCommand('bin/console doctrine:database:drop --if-exists --force');
$cli->seeResultCodeIs(0);
$cli->runShellCommand('bin/console doctrine:database:create');
$cli->seeResultCodeIs(0);
$this->writeln('Running Doctrine Migrations...');
$cli->runShellCommand('bin/console doctrine:migrations:migrate --no-interaction');
$cli->seeResultCodeIs(0);
$this->writeln('Test database recreated');
} catch (\Exception $e) {
$this->writeln(
sprintf(
'An error occurred whilst rebuilding the test database: %s',
$e->getMessage()
)
);
}
}
}
and registered;
// codeception.yml
extensions:
enabled:
- \DatabaseMigrationExtension
Output (-vv or higher also displays the output of the DB & Migration commands);
I always create a bash script to do this, or a Makefile.
bash command
My ./runtests.sh scripts contains
#!/bin/bash
./bin/console command:for:migrations
./bin/phpunit
Makefile
Same with Makefile
.FOO: testsuite
testsuite:
./runtests.sh
or
.FOO: testsuite
testsuite:
./bin/console command:for:migrations
./bin/phpunit
why I prefer Makefile
Recently I added this script in my .bash_profile that allow me to autocomplete from bash all target made in makefile (very easy because you dont need anymore to remember all commands, but just make and tab).
complete -W "`grep -oE '^[a-zA-Z0-9_.-]+:([^=]|$)' Makefile | sed 's/[^a-zA-Z0-9_.-]*$//'`" make
Thus, .. you can create target like:
runtests
runtests_with_fixtures
migrations
runtests_with_migrations
...
and so on
My suggestion is to create your custom and easy way to run commands.
Here a way to run all or just one command usgin make
.FOO: dropforce
dropforce:
bin/console doctrine:database:drop --force
.FOO: dbcreate
dbcreate:
bin/console doctrine:database:create
.FOO: migrate
migrate:
bin/console doctrine:migrations:migrate
.FOO: suite
suite: dropforce dbcreate migrate
With Codeception 4 you can do it without Cli module:
$symfony = $this->getModule('Symfony');
$symfony->runSymfonyConsoleCommand('doctrine:database:drop',['--if-exists'=>true, '--force'=>true]);
$symfony->runSymfonyConsoleCommand('doctrine:database:create');
$symfony->runSymfonyConsoleCommand('doctrine:migrations:migrate', ['--no-interaction'=>true]);
I would like to execute the following command : composer update in my controller in laravel, however this one does not work.
On the other hand the command composer info works perfectly.
When I execute composer update in a command prompt all my dependencies are correctly updated in the laravel vendor file but when I try to execute composer update in my controller nothing happens.
here is my code :
$data['output'] = shell_exec( 'cd '. base_path() .' && composer update' );
dd($data);
and here is the result :
array:1 [▼
"output" => null
]
Could you help me to understand why composer update does not work in a controller ?
I would like to update my dependencies in a controller without the command prompt.
Thank you.
From the php docs for shell_exec():
The output from the executed command or NULL if an error occurred or the command produces no output.
Sounds like you'd be better off using passthru() instead as that will give you the erroneous output.
Speaking of erroneous, this is idea sounds like a recipe for unmitigated disaster.
I do everything by-the-book:
Installed fresh Laravel 5.3.9 app (all my non-fresh apps produce the same error)
run php artisan make:auth
create migrations for a new table
`php artisan make:migration create_quotations_table --create=quotations
Schema::create('quotations', function (Blueprint $table) {
$table->increments('id');
$table->string('text');
// my problem persists even with the below two columns commented out
$table->integer('creator_id')->unsigned()->index('creator_id');
$table->integer('updater_id')->unsigned()->index('updater_id');
$table->softDeletes();
$table->timestamps();
});
Then I run php artisan migrate
Then I define a new seed php artisan make:seeder QuotationsTableSeeder
The complete content of the file, after I add a simple insert:
<?php
use Illuminate\Database\Seeder;
class QuotationsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('quotations')->insert([
'text' => str_random(10),
]);
}
}
Then I run php artisan db:seed
problem
it simply doesn't work. No feedback presented, no errors in log file.
The probem persists in both my local environment (Win7, newest WAMP server)
and my Digital Ocean VPS powered by Ubuntu 16.04.
All the above steps I took in several separate apps - for no result. Also under Laragon 2.0.5 server.
what I have tried
php artisan optimize as suggested here.
composer dump-autoload i php artisan clear-compiled also have brought no results
I also tried to seed just following the official docs example - failed.
I added use DB; to the seed file - still no result.
to do
help!!! How come they don't work?
Are you calling your seeder inside the DatabaseSeeder class? This way:
database/seeds/DatabaseSeeder.php
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call(QuotationTableSeeder::class);
}
}
Or, add the --class option when using the php artisan db:seed command, this way:
php artisan db:seed --class="QuotationTableSeeder"
After creating or removing your seeders, don't forget to run the following command:
composer dump-autoload
NB:
Please use with caution on DEV ENVIRONMENT and/or DISPOSABLE DATABASES ONLY
If anybody else is having issues with migrating AND seeding at the same time, please try
php artisan migrate:fresh --seed
Worked for me..
I need to migrate my database schema for some unit tests I'm writing, and one of these migrations is included in a package. Normally, from the command line, I'd run this command:
php artisan migrate --package=tappleby/laravel-auth-token
And to run my own migrations in code I'd do:
Artisan::call('migrate');
However, I can't seem to get Artisan to run package migrations from inside code. I've tried this:
Artisan::call('migrate --package=tappleby/laravel-auth-token');
but that results in an unknown command error. I've also tried these:
Artisan::call('migrate', '--package=tappleby/laravel-auth-token');
Artisan::call('migrate', ['--package=tappleby/laravel-auth-token']);
Artisan::call('migrate', ['package=tappleby/laravel-auth-token']);
None of the above works. What's the correct way of running package migrations in my code?
I believe the correct syntax uses an associative array for the command parameters, where the item key is the name of the parameter and the item value is the value of the parameter. This should work in your case:
Artisan::call('migrate', ['--package' => 'tappleby/laravel-auth-token']);
I did it with --path:
Artisan::call('migrate', ['--path' => 'vendor/systeminc/laravel-admin/src/database/migrations']);
So my migrations folder looks like this since I have dozens of tables it keeps things organized and clean:
migrations/
create_user_table.php
relations/
translations/
I'm trying to do a refresh all migrations and seed but it seems like I've run into a slight hiccup where I don't know the artisan command to run migrations recursively (i.e. run migrations in the relations and translations folders as well).
I've tried adding --path="app/database/migrations/*" however it spat out an error. Does anyone know the solution to this?
The only way to do it right now is to manually go through all the migrations. That is, you have to run the migration command on each of your subfolders:
php artisan migrate --path=/app/database/migrations/relations
php artisan migrate --path=/app/database/migrations/translations
However, what you can do is easily extend the artisan system to write your own migrate command that will iterate through all folders under the migrations folder, create these commands for you and run them.
You can also simply write a shell script if you don't want to get into doing this via artisan
Edit: for Laravel >= 5.0, the correct commands to migrate migration files in sub directories would be:
php artisan migrate --path=/database/migrations/relations
php artisan migrate --path=/database/migrations/translations
This add to boot method in AppServiceProvider
$mainPath = database_path('migrations');
$directories = glob($mainPath . '/*' , GLOB_ONLYDIR);
$paths = array_merge([$mainPath], $directories);
$this->loadMigrationsFrom($paths);
Now you use can php artisan migrate and also php artisan migrate:back
You can also use a wildcard, like so:
php artisan migrate --path=/database/migrations/*
You can use the following command to do this recursively:
php artisan migrate --path=/database/migrations/**/*
**/* is also known as the globstar
Before this works you must check if your bash supports the globstar.
You can do this by executing shopt and checking for globstar.
Globstar is supported by default by most server distributions but might not work on MAC.
For more on globstar see: https://www.linuxjournal.com/content/globstar-new-bash-globbing-option
In Laravel 5 the database folder sits alongside the app folder by default. So you could run this to migrate a single folders migrations:
php artisan migrate --path=/database/migrations/users
You can try this package nscreed/laravel-migration-paths. By default all sub directories inside the migrations folder will be autoloaded. Even you can add any directories very easily.
'paths' => [
database_path('migrations'),
'path/to/custom_migrations', // Your Custom Migration Directory
],
Don't need any special command just the generic: php artisan migrate will do your tasks.
I rewrote the MigrationServiceProvider:
- registerResetCommand()
- registerStatusCommand()
- registerMigrateCommand()
There you can register your own commands:
class MigrateCommand extends Illuminate\Database\Console\Migrations\MigrateCommand
After that you just need to extend youd directories:
protected function getMigrationPaths()
Or you just register the paths on application boot.
I've already done my solution before I knwewd about '$this->loadMigrationsFrom'.
A Simple solution is to create an Artisan Command for example (migrate:all),
then inside handle function define migrate command for each sub directories as mentioned bellow.
Artisan::call('migrate', [
'--path' => '/database/migrations/employee'
]);
Only relative path works for me (in Laravel 5.7):
php artisan migrate --path=database/migrations/your-folder-with-migrations
This works at laravel 8
php artisan migrate --path=database/migrations/tenant
It is a not a "direct" solution but i suggest you to look at Modularity into your laravel project.
Modules can segment your application in several smaller "folders" and bring migration, seeds, classes, routes, controllers, commands together in easily maintainable folders.
This package is a good start : https://github.com/pingpong-labs/modules
No changes are necessary, whenever you need it, use this command:
php artisan migrate --path=database/migrations/*
If you want a shortcut, you can include that in your composer.json:
"scripts": {
"migrate": [
"#php artisan migrate --force --path=database/migrations/*"
]
}
Then just use composer migrate in the terminal.
add in app/Providers/AppServiceProvider.php the path of your migration folder, you can add a string or an array
public function register()
{
$this->registerMigrations();
}
protected function registerMigrations()
{
return $this->loadMigrationsFrom(__DIR__ . '/../../database/migrations/**/*');
}
A Simple Laravel solution is to create a gulp task (say migrate-others).
var elixir = require('laravel-elixir');
var gulp = require('gulp');
var shell = require('gulp-shell')
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss');
});
// Our Task
gulp.task('migrate-others', shell.task([
'php artisan migrate --path=/app/database/migrations/relations',
'php artisan migrate --path=/app/database/migrations/translations',
]));
Now you can simply call
gulp migrate-others
Here you go!
function rei($folder)
{
$iterator = new DirectoryIterator($folder);
system("php artisan migrate --path=" . $folder);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
echo $fileinfo->getFilename() . "\n";
rei($folder . $fileinfo->getFilename() . '/');
}
}
}
rei('./database/');