Skip to content

Instantly share code, notes, and snippets.

@nasirkhan
Last active July 22, 2020 11:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nasirkhan/63320617050f6f8490795e1760ec03cf to your computer and use it in GitHub Desktop.
Save nasirkhan/63320617050f6f8490795e1760ec03cf to your computer and use it in GitHub Desktop.
Call laravel routes via command line

http://stackoverflow.com/questions/28866821/call-laravel-controller-via-command-line

There is no way so far (not sure if there will ever be). However you can create your own Artisan Command that can do that. Create a command CallRoute using this:

php artisan make:console CallRoute

This will generate a command class in app/Console/Commands/CallRoute.php. The contents of that class should look like this:

<?php namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Illuminate\Http\Request;

class CallRoute extends Command {

    protected $name = 'route:call';
    protected $description = 'Call route from CLI';

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

    public function fire()
    {
        $request = Request::create($this->option('uri'), 'GET');
        $this->info(app()['Illuminate\Contracts\Http\Kernel']->handle($request));
    }

    protected function getOptions()
    {
        return [
            ['uri', null, InputOption::VALUE_REQUIRED, 'The path of the route to be called', null],
        ];
    }

}

You then need to register the command by adding it to the $commands array in app/Console/Kernel.php:

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

You can now call any route by using this command:

php artisan route:call --uri=/route/path/with/param

Mind you, this command will return a response as it would be sent to the browser, that means it includes the HTTP headers at the top of the output.

@HeartlandTechie
Copy link

Command "make:console" is not defined.

? php artisan make:command CallRoute

@Fab1en
Copy link

Fab1en commented Jan 20, 2020

There is a typo : you should use command not console
php artisan make:command CallRoute

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment