Search code examples
phplaravellaravel-artisan

PHP Laravel - Best practice to run controller with variable from command


I am trying to setup a command in Laravel, that should run every day at 18:30.

I have a function in a controller, I wish to run (is this the correct place to put a function that should only be run from the command line?):

ReportController.php:

public function process($reportName)
{
   return("Function process has run correctly. Report: ".$reportName." ");
}

I have created a command file:

ProcessReports.php

namespace App\Console\Commands;

use App\Http\Controllers\ReportController;
use Illuminate\Console\Command;

class ProcessReports extends Command
{

    protected $signature = 'report:process {reportName}';
    protected $description = 'Process reports from FTP server';

    public function __construct()
    {
        parent::__construct();

    }
    public function handle()
    {
        //
        $ReportController = new ReportController(); 
        $ReportController->process($reportName);      
    }
}

Furthermore, in my Kernel.php I have registered my command:

Kernel.php:

 protected $commands = [
            'App\Console\Commands\ProcessReports',
 ];

 protected function schedule(Schedule $schedule)
 {
    $schedule->command('report:process MyReport')
               ->dailyAt('18:30');                        
 } 

I then try to run my command like: $ php artisan report:process MyReport. But this is not possible. It gives me this error:

Undefined variable: reportName

Can anyone guide me on how to create commands, which can run my function daily?


Solution

  • You need to get the argument first, change your handle() method to:

    public function handle()
    {
        //
        $reportName = $this->argument('reportName');
        $ReportController = new ReportController(); 
        $ReportController->process($reportName);      
    }
    

    Documentation: Artisan Command I/O