Laravel 5动态运行迁移

mdi*_*n18 6 php laravel 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';
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Artisan::call('migrate', array('--path' => 'app/migrations'));
Run Code Online (Sandbox Code Playgroud)

但是,这在laravel 5中无效,我该如何处理?

cee*_*yoz 19

Artisan::call('migrate', array('--path' => 'app/migrations'));
Run Code Online (Sandbox Code Playgroud)

将在Laravel 5中工作,但你可能需要进行一些调整.

首先,由于Laravel 5的命名空间,你需要use Artisan;在文件顶部放一行(在哪里use Illuminate\Support\ServiceProvider...).(你也可以这样做\Artisan::call- 这\很重要).

您可能还需要这样做:

Artisan::call('migrate', array('--path' => 'app/migrations', '--force' => true));
Run Code Online (Sandbox Code Playgroud)

--force是必要的,因为Laravel默认会在生产中提示你是/否,因为它是一个潜在的破坏性命令.如果没有--force,你的代码将只是坐在那里旋转的轮子(Laravel的,等待来自CLI的响应,但你不是命令行).

在此输入图像描述

我会鼓励你做这个东西的地方其他boot服务提供商的方法.这些可能是繁重的调用(依赖于您不希望在每个网页浏览中进行的文件系统和数据库调用).请考虑使用显式安装控制台命令或路由.

  • @ mdixon18回滚可能非常讨厌 - 我不会自动化.[据我所知](http://stackoverflow.com/questions/30287896/rollback-one-specific-migration-in-laravel)没有Artisan命令来回滚*特定*迁移,所以你最终可能会回滚错误的一个,吹走了数据.我会通过您的应用提供的Artisan控制台命令进行安装. (2认同)