Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call laravel controller via command line

Tags:

php

laravel

In kohana framework I can call controller via command line using

php5 index.php --uri=controller/method/var1/var2 

Is it possible to call controller I want in Laravel 5 via cli? If yes, how to do this?

like image 790
user3345632 Avatar asked Mar 04 '15 23:03

user3345632


People also ask

How do you call a controller in Laravel?

use App\Http\Controllers\UserController; Route::get('/user/{id}', [UserController::class, 'show']); When an incoming request matches the specified route URI, the show method on the App\Http\Controllers\UserController class will be invoked and the route parameters will be passed to the method.

How do I use console commands in Laravel?

Simply add a new command like $schedule->command('command:name')->hourly(); inside schedule function.


1 Answers

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.

like image 138
Bogdan Avatar answered Sep 20 '22 19:09

Bogdan