Chad Priddle
Chad Priddle

Reputation: 672

Laravel - Pass variable to controller from kernel schedule

Using laravel schedule command in Kernel.php can you pass a variable to the controller?

Kernel.php

$schedule->call('App\Http\Controllers\TestController@fetchInvoices(20)')->everyMinute();
$schedule->call('App\Http\Controllers\TestController@fetchInvoices(100)')->everyFiveMinutes();

TestController.php

public function fetchInvoices($id){
      dd($id);
}

My goal is to have 2 crons run at different times without having to duplicate the functions.

Upvotes: 0

Views: 3118

Answers (3)

user3247268
user3247268

Reputation: 11

Laravel 8 has a little change in the implementation, you will need to pass the name of the variable in an array as defined in the method you are calling. Below code should work for you.

$schedule->call('App\Http\Controllers\TestController@fetchInvoices', ['id' => 10])->everyMinute();

$schedule->call('App\Http\Controllers\TestController@fetchInvoices', ['id' => 10])->everyFiveMinutes();

Upvotes: 1

Ben Sholdice
Ben Sholdice

Reputation: 407

the Schedule::call() function looks like it can accept parameters:

/**
 * Add a new callback event to the schedule.
 *
 * @param  string|callable  $callback
 * @param  array  $parameters
 * @return \Illuminate\Console\Scheduling\CallbackEvent
 */
public function call($callback, array $parameters = [])
{
    $this->events[] = $event = new CallbackEvent(
        $this->eventMutex, $callback, $parameters
    );

    return $event;
}

so try:

$schedule->call('App\Http\Controllers\TestController@fetchInvoices', array('10'))->everyMinute();

Upvotes: 1

Craig
Craig

Reputation: 36

I'm no Laravel expert but I don't think using a Controller is the right method here.

Try and build the fetchInvoices method into an Artisan command with options. https://laravel.com/docs/5.8/artisan#writing-commands

Artisan commands can easily be scheduled. https://laravel.com/docs/5.8/scheduling#scheduling-artisan-commands

Upvotes: 1

Related Questions