Laravel - 调用 Artisan 命令并等待结果

标签 laravel laravel-artisan

我试图在 Controller 中调用一个非常耗时的 Artisan 命令(它在 20-90 秒内执行),但我有两个问题。首先,该命令似乎根本没有执行(如果我返回输出,它只会返回“0”)。

其次,另一部分(返回文件)不等待命令执行(但它可以与第一部分相关)。这是我的代码:

public function returnZip()
{
    // just a failsafe, in case if scheduled command did not created the file yet
    if( ! file_exists( storage_path( '/app/exports/' . date('Y_m_d') . '.zip' ) ) ){
        Artisan::call('maximus:export');
    }

    return response()->file( storage_path( '/app/exports/' . date('Y_m_d') . '.zip' ) );
}

如何从路由/ Controller 正确执行 Artisan 命令并等待它完成任务?

编辑

我尝试进一步调试这个问题,发现从路由/ Controller 调用时根本没有执行该命令。

尝试过这个:

Route::get('/test', function(){
    Artisan::call('maximus:export');
    return ['ok'];
});

我的命令应该创建一个文件:

public function handle()
{
    exec('touch /some/path/storage/app/exports/test');
 }

当我在终端中运行此命令时,正在创建文件,但当我点击路线时,文件却没有创建。有任何想法吗?

最佳答案

好的,我启动了 Laravel 并测试了它。我的命令是:

public function handle()
{
    exec('touch ' . storage_path(str_random(16) . '.txt'));
}

通过调用 Artisan::call(),它在终端和路由中都能完美运行。

一个疯狂的猜测:www-data 用户(或者您的网络服务器运行的 PHP 的任何用户)是否有足够的权限来写入文件?

关于Laravel - 调用 Artisan 命令并等待结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42298587/

相关文章:

javascript - VueJS 和 Laravel : DELETE Request turns into MethodNotAllowedHttpException

html - 删除仅用于登录的 Chrome 自动完成的输入背景颜色

laravel - 如何在包中安排 Artisan 命令?

Laravel 5 - artisan 种子 [ReflectionException] 类 SongsTableSeeder 不存在

php - Laravel - php artisan 制作 :model Project Doesnt Work

php - 拉维尔 : I can't use Request object two times at the same function

php - SQLSTATE[HY000] : General error: 1215 Cannot add foreign key constraint laravel 9

php - 在 Laravel 验证期间获取列表的索引并显示在错误消息中

php - Laravel - 读取配置变量

php - 我是 ubuntu 的新手。我已经安装了 phpstorm 并尝试运行 composer 但它没有运行