Home > front end >  Laravel: how to simplify artisan commands?
Laravel: how to simplify artisan commands?

Time:12-01

I want to simplify the following artisan commands because I have several databases and the migrations for each database are stored in a separate folder.

php artisan make:migration {{name}} --path=/database/migrations/{{folder}}

php artisan migrate:rollback  --path=/database/migrations/{{folder}}

to

php artisan make:migration {{name}} {{folder}}

php artisan migrate:rollback {{folder}}

Is this possible and if so how can I implement it?

CodePudding user response:

Since this is not an option in the Laravel commands, a way to implement this yourself is by writing you own commands that call other artisan commands.

To do so, in your terminal write php artisan make:command MigrateWithPath to create a new command at app/Console/Commands/MigrateWithPath.php. Then, you can call the vanilla implementation Laravel provides at (vendor\laravel\framework\src) \Illuminate\Database\Console\Migrations\MigrateMakeCommand but than in a way that you specify.

Be sure though that the name of your new command needs to be different from the Laravel one, to prevent recursions. Therefore, I have prefixed the name with app: for example to be like app:make:migration.

Take a look at the following suggestion:

class MigrateWithPath extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:make:migration {name : The name of the migration}
        {folder? : The location where the migration file should be created}';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->call('make:migration', [
            'name' => $this->argument('name'),
            '--path' => '/database/migrations/' . $this->argument('folder'),
        ]);

        return 0;
    }

Then do the same for the rollback command.

  • Related