Laravels Artisan::call('migrate:status') 作为 json 响应



我想在控制器中获取我的 laravel 应用程序的迁移状态作为 json 响应,我尝试

$migratiorns = Artisan::call('migrate:status');
return response()->json($migratiorns);

Artisan::call返回一个整数0

我应该为我的案例使用什么来获得所需的响应?

$migration的值将是您在命令行上看到的输出,这是一种表,它基本上是一个无法转换为 json 的字符串值。

一个简单的方法是:

Artisan::call('migrate:status');
dd(Artisan::output());

这个问题很老了,但我遇到了同样的问题,没有找到任何解决方案,所以我做了一个小的辅助函数来即时获取待处理的迁移,也许它会帮助其他人:

function getPendingMigration($migrationsFolderPath = false, $toJson = false)
{
    $migrationsFolderPath = $migrationsFolderPath ?: database_path('/migrations');
    $migrations = app('migrator')->getMigrationFiles($migrationsFolderPath);
    $pendingMigrations = [];
    foreach ($migrations as $migration => $fullpath){
        if(!IlluminateSupportFacadesDB::table('migrations')->where('migration', $migration)->exists())
            array_push($pendingMigrations, $migration);
    }
    return $toJson ? json_encode($pendingMigrations) : $pendingMigrations;
}

在这里 ini 我的控制台代码

protected $signature = 'command:name {json?}';

INI 手柄功能

public function handle()
{
    $json = $this->argument('json');
    if($json){
        $a = ['foo'=>
            ['bar', $json]
        ];
        $a = collect($a);
        $this->info($a->toJson());
    } else {
        $this->info('Display this on the screen');
    }
}

只需运行

php artisan command:name -json 

将获得 JSON 输出

最新更新