Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run command in Laravel kernel after another successful command

I'm creating a custom command which will truncate a table every thirty minutes in the console kernel (for development purposes). I want to run another right after the previous command.

P.S: I have an if statement which prevents running these commands on the production server.

$schedule->command('db:seed')->after(function () use ($schedule) : void {
    $schedule->command('my-command:remove-users-from-tables')
        ->everyThirtyMinutes()
        ->environments(['demo', 'local']);
});

I expect to run the seeder right after "my-command" runs successfully every thirty minutes. However, in this way, only db:seed runs.

like image 766
Mohamad Karimisalim Avatar asked Nov 02 '25 17:11

Mohamad Karimisalim


2 Answers

I have checked the source code for Illuminate\Console\Scheduling\Schedule class.

I think when we say:

$schedule->command(...);

The artisan command will be scheduled, not run straightaway.

So when you write like this:

$schedule->command('first-command')->after(function () use ($schedule) {
    $schedule->command('second-command');
});

The second command will be registered, not run right after the first command.

So the best approach that I can think of is run the second command inside the first command according to this link

You might try something like this:

namespace App\Console\Commands;

use Illuminate\Console\Command;

class RemoveUsersFromTable extends Command
{
    public function handle()
    {
        // Do something to remove users from table.

        $this->call('db:seed');
    }
} 
like image 188
Kevin Bui Avatar answered Nov 05 '25 08:11

Kevin Bui


If you want to run B after A you need to schedule A and AFTER that run B:

$schedule->command('my-command:remove-users-from-tables')
        ->everyThirtyMinutes()
        ->after(function() {
            $this->artisan->call('db:seed');
        });
like image 39
mwallisch Avatar answered Nov 05 '25 06:11

mwallisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!