daninthemix
daninthemix

Reputation: 2570

Command-line scripts in Laravel?

I have some command line scripts that I would like to modify to use Laravel's features (Eloquent etc).

How do I do that? I am aware that Laravel bootstraps from the index.html file. Is there any provision for running command-line apps / scripts?

Upvotes: 7

Views: 27695

Answers (2)

Artur Subotkevič
Artur Subotkevič

Reputation: 1939

  1. Make a command using php artisan make:command FancyCommand.
  2. In /app/Console/Commands/FancyCommand.php find a protected variable $signature and change it's value to your preferred signature:

    protected $signature = 'fancy:command';
    
  3. Code in the handle() method will be executed:

    public function handle()
    {
        // Use Eloquent and other Laravel features...
    
        echo 'Hello world';
    }
    
  4. Register your new command in the /app/Console/Kernel.php by adding your command's class name to $commands array.

    protected $commands = [
        // ...
        Commands\FancyCommand::class,
    ];
    
  5. Run your new command: php artisan fancy:command.

Upvotes: 27

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

Yes, you can use Artisan commands:

Artisan::command('my:command', function () {
    // Here you can use Eloquent
    $user = User::find(1);

    // Or execute shell commands
    $output = shell_exec('./script.sh var1 var2');
});

Then run it using

user@ubuntu: php artisan my:command

Check the docs: https://laravel.com/docs/5.3/artisan

You can also use the scheduler: https://laravel.com/docs/5.3/scheduling

Upvotes: 11

Related Questions