Laravel 5 动态运行迁移

6 浏览
0 Comments

Laravel 5 动态运行迁移

所以,我已经在结构中创建了自己的博客包Packages/Sitemanager/Blog,并有一个服务提供者,看起来像下面这样:

namespace Sitemanager\Blog;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
class BlogServiceProvider extends LaravelServiceProvider {
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot() {
        $this->handleConfigs();
        $this->handleMigrations();
        $this->handleViews();
        $this->handleRoutes();
    }
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register() {
        // Bind any implementations.
        $this->app->make('Sitemanager\Blog\Controllers\BlogController');
    }
    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides() {
        return [];
    }
    private function handleConfigs() {
        $configPath = __DIR__ . '/config/blog.php';
        $this->publishes([$configPath => config_path('blog.php')]);
        $this->mergeConfigFrom($configPath, 'blog');
    }
    private function handleTranslations() {
        $this->loadTranslationsFrom(__DIR__.'/lang', 'blog');
    }
    private function handleViews() {
        $this->loadViewsFrom(__DIR__.'/views', 'blog');
        $this->publishes([__DIR__.'/views' => base_path('resources/views/vendor/blog')]);
    }
    private function handleMigrations() {
        $this->publishes([__DIR__ . '/migrations' => base_path('database/migrations')]);
    }
    private function handleRoutes() {
        include __DIR__.'/routes.php';
    }
}

现在,我想要做的是,在安装过程中动态地运行迁移(如果它们以前从未运行过)。我在旧的文档中看到过可以这样做:

Artisan::call('migrate', array('--path' => 'app/migrations'));

然而,在 Laravel 5 中,这是无效的。我该怎么做?

admin 更改状态以发布 2023年5月22日
0
0 Comments

发布包后:

php artisan vendor:publish --provider="Packages\Namespace\ServiceProvider"

您可以使用以下命令执行迁移:

php artisan migrate

Laravel 自动追踪已执行的迁移,并相应地运行新的迁移。

如果您想在 CLI 之外执行迁移,例如在路由中,您可以使用Artisan facade:

Artisan::call('migrate')

您可以将可选参数(例如 force 和 path)作为数组传递给 Artisan::call 的第二个参数。

继续阅读:

0
0 Comments

Artisan::call('migrate', array('--path' => 'app/migrations'));

在Laravel 5中可以正常工作,但你可能需要进行一些调整。

首先,在你的文件的最上面需要一个use Artisan;行(在use Illuminate\Support\ServiceProvider...的位置),因为Laravel 5的命名空间。 (你也可以这样做:\Artisan::call - 注意\是重要的)。

您可能还需要执行以下操作:

Artisan::call('migrate', array('--path' => 'app/migrations', '--force' => true));

需要--force,因为在生产环境中,Laravel默认会向您提示一个是/否的问答,因为这是一个潜在的破坏性命令。没有--force,您的代码就只会在那里转圈(Laravel在等待CLI的响应,但您不在CLI中)。

enter image description here

我鼓励你把这些东西放到服务提供者的boot方法之外的地方。 这些可能是重调用(依赖于文件系统和数据库调用,您不希望在每个页面上调用)。 考虑使用显式的安装控制台命令或路由。

0