7

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?

1
  • A good example for Laravel 9: positronx.io/… Commented Apr 24, 2023 at 7:57

2 Answers 2

27
  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.

Sign up to request clarification or add additional context in comments.

2 Comments

Although this is actually the better way of doing it (compared to the closure based method that's being upvoted), you managed to make it seem more complicated that it actually is some how.
Thank you, very helpful! Also in Laravel7 you don't need to do step 4
11

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

2 Comments

Thanks. I should've mentioned I'm actually using Lumen - does the above still apply?
Where does one put this command code? Looks like console.php is the place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.