9

Is there a way to execute some artisan commands, using custom artisan command, like I want to make a custom command called:

$ php artisan project:init 

which will execute some commands like php artisan migrate:refresh and php artisan db:seed and php artisan config:clear

Is there any way to do this?

1
  • Hello, Can you accept my answer? Commented Jul 16, 2021 at 14:51

2 Answers 2

17

There is 2 way to group commands or call it from another command.

Variant 1: Create new Console Command in routes/console.php . routes/console.php

Artisan::command('project:init', function () {
    Artisan::call('migrate:refresh', []); // optional arguments
    Artisan::call('db:seed');
    Artisan::call('config:clear');
})->describe('Running commands');

Variant 2: According to docs: https://laravel.com/docs/7.x/artisan#calling-commands-from-other-commands

Create new command using command line:

$ php artisan make:command ProjectInit --command project:init

This will create new file: App\Console\Commands\ProjectInit

In that ProjectInit class's handle method you can call another commands:

public function handle(){
  $this->call('migrate:refresh', []); // optional arguments
  $this->call('db:seed');
  $this->call('config:clear');
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, i've made the command by reading the docs as you've mentioned and it worked after i've called those commands as the docs mentioned laravel.com/docs/7.x/…
Glad to help you, please close question by accepting this answer. Thank you
5

Yes, you can call console commands programmatically

https://laravel.com/docs/7.x/artisan#programmatically-executing-commands https://laravel.com/docs/7.x/artisan#calling-commands-from-other-commands

I've used it on a number of occasions where i've wanted to bundle commands together. For example:

$this->call('custom:command1', [
    '--argument1' => 'foo',
]);

$this->call('custom:command2', [
    '--argument1' => 'bar',
]);

1 Comment

Glad i could help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.