Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command-line scripts in Laravel?

Tags:

php

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?

like image 238
daninthemix Avatar asked Dec 06 '16 10:12

daninthemix


2 Answers

  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.

like image 88
Artur Subotkevič Avatar answered Oct 22 '22 23:10

Artur Subotkevič


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

like image 32
Antonio Carlos Ribeiro Avatar answered Oct 23 '22 00:10

Antonio Carlos Ribeiro