我有这样的控制器
public function store(Request $request)
{
Artisan::call("php artisan infyom:scaffold {$request['name']} --fieldsFile=public/Product.json");
}
显示错误
"php artisan infyom"命名空间中没有定义任何命令。
当我在CMD中运行此命令时,它可以正常工作
您需要删除php artisan
部分并将参数放入数组中才能使其工作:
public function store(Request $request)
{
Artisan::call("infyom:scaffold", ['name' => $request['name'], '--fieldsFile' => 'public/Product.json']);
}
https://laravel.com/docs/5.2/artisan#calling-通过代码的命令
如果有简单的工作要做,可以从路由文件中完成。例如,要清除缓存。在终端中,它将是php手工缓存:清除在路由文件中,它是:
Route::get('clear_cache', function () {
'Artisan::call('cache:clear');
dd("Cache is cleared");
});
要从浏览器运行此命令,只需转到您的项目路线并转到clear_cache即可。示例:
http://project_route/clear_cache
除了在另一个命令中,我真的不确定我能想出这样做的好理由。但是,如果你真的想从控制器(或模型等)调用Laravel命令,那么你可以使用Artisan::call()
Artisan::call('email:send', [
'user' => 1, '--queue' => 'default'
]);
一个有趣的功能是Artisan::queue()
,它将在后台(由队列工作人员)处理命令:
Route::get('/foo', function () {
Artisan::queue('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
});
如果你从另一个命令中调用一个命令,你不必使用Artisan::call
方法——你可以做这样的事情:
public function handle()
{
$this->call('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
}
来源:https://webdevetc.com/programming-tricks/laravel/general-laravel/how-to-run-an-artisan-command-from-a-controller/
删除php手工部分并尝试:
Route::get('/run', function () {
Artisan::call("migrate");
});
命令作业,
路径:{项目路径}/app/Console/Commands/RangeDatePaymentsConsoleCommand.php
这是使用artisan命令运行的作业。
class RangeDatePaymentsConsoleCommand extends Command {
protected $signature = 'batch:abc {startDate} {endDate}';
...
}
web.php,
路径:{项目路径}/routes/web.php
php管理所有请求并路由到相关控制器,并且可以为多个控制器和同一控制器内的多个功能提供多个路由。
$router->group(['prefix' => 'command'], function () use ($router) {
Route::get('abc/start/{startDate}/end/{endDate}', 'CommandController@abc');
});
CommandController.php,
路径:{项目路径}/app/Http/Controllers/CommandController.php
这个控制器是为处理手工命令而创建的,名称可以不同,但应该与web.php控制器名称和函数名称相同。
class CommandController extends Controller {
public function abc(string $startDate, string $endDate) {
$startDate = urldecode($startDate);
$endDate = urldecode($endDate);
$exitCode = Artisan::call('batch:abc',
[
'startDate' => $startDate,
'endDate' => $endDate
]
);
return 'Command Completed Successfully. ';
}
请求:http://127.0.0.1:8000/command/abc/start/2020-01-01 00:00:00/end/2020-06-30 23:59:59
它可以在启动服务器后通过web浏览器或Postman进行访问。运行此命令在{projectpath}启动php服务器
php -S 127.0.0.1:8080 public/index.php
方法#1:使用路由
Route::get('run-it', function () {
(new 'App'Console'Commands'ThisIsMyCommand())->handle();
});
方法#2:使用命令行
php artisan command:this_is_my_command