Call Laravel Controller via Command Line

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

For Laravel 5.3 or greater you need to use make:command instead:

php artisan make:command 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.

Call a Controller method from a Command in Laravel

If your controller does not have any required parameters, you can just create the controller as a new object, and call the function.

$controller = new TransactionController();
$controller->assignUser([
'transId' => $trans_id,
'userId' => $user_id
]);

Laravel Run function from console command

Solved!
I've just placed on handle controller's class name and called the function as following:

$x = new HelloWorldController(); 
echo $x->helloWorld();

It worked!

How to execute command from the controller and pass parameters to it? LARAVEL

I would have to guess that you are passing a Collection as the second argument to call. You would have to ask that Collection for the underlying array:

Artisan::call('fidelizaleads:quotesWithoutProjects', $translateWithouthProyect->toArray());

You can use toArray() on the Collection to get the array.

Though I am not sure what passing that array is going to do as you don't have any parameters for that command and the array is usually an associative array.

Laravel 5 - how to run a Controller method from an Artisan Command?

Try to use use Full\Path\To\Your\Controller; in your command code and use method statically:

public static function someStaticMethod()
{
return 'Hello';
}

In your command code:

echo myClass::someStaticMethod();


Related Topics



Leave a reply



Submit