This is what you need : http://laravel.com/docs/5.1/scheduling
Jul 5, 2015
11
Level 1
how call controller from a command line ?
hi to everyone , i want to make a job that run code every hour so i want to call controller from command line ? can anyone understand me how to do this ? -- thanks>>
Level 56
Again, it is a bad idea to "run" a controller.
Create a service class (a bare class) that do what you want.
namespace App\Services;
class FooService
{
public function performFoo ()
{
// Do what you need
}
}
Then inject it in the controller actions you want and use it :
namespace App\Http\Controllers;
// ...
use App\Services\FooService;
class SomeController extends Controller
{
public function SomeAction (FooService $foo_service)
{
$foo_service->performFoo();
}
}
Then create a command and inject the service to use it :
namespace App\Console\Commands;
// ...
use App\Services\FooService;
class Foo extends Command
{
protected $signature = 'foo';
protected $description = 'Perform foo';
private $foo_service;
public function __construct(FooService $foo_service)
{
$this->foo_service = $foo_service;
}
public function handle ()
{
$this->foo_service->performFoo();
}
}
Then in app/Console/Kernel.php set the scheduling :
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
\App\Console\Commands\Inspire::class,
\App\Console\Commands\Foo::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('inspire')->hourly();
$schedule->command('foo')->hourly();
}
}
3 likes
Please or to participate in this conversation.