Laravel 5 dynamically run migrations

前端 未结 3 1269
天命终不由人
天命终不由人 2021-01-05 02:11

so I have created my own blog package in a structure of Packages/Sitemanager/Blog I have a service provider that looks like the following:

names         


        
相关标签:
3条回答
  • 2021-01-05 02:23
    Artisan::call('migrate', array('--path' => 'app/migrations'));
    

    will work in Laravel 5, but you'll likely need to make a couple tweaks.

    First, you need a use Artisan; line at the top of your file (where use Illuminate\Support\ServiceProvider... is), because of Laravel 5's namespacing. (You can alternatively do \Artisan::call - the \ is important).

    You likely also need to do this:

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

    The --force is necessary because Laravel will, by default, prompt you for a yes/no in production, as it's a potentially destructive command. Without --force, your code will just sit there spinning its wheels (Laravel's waiting for a response from the CLI, but you're not in the CLI).

    I'd encourage you to do this stuff somewhere other than the boot method of a service provider. These can be heavy calls (relying on both filesystem and database calls you don't want to make on every pageview). Consider an explicit installation console command or route instead.

    0 讨论(0)
  • 2021-01-05 02:29

    For the Laravel 7(and properly 6):

    use Illuminate\Support\Facades\Artisan;
    
    
    Artisan::call('migrate');
    

    will greatly work.

    0 讨论(0)
  • 2021-01-05 02:30

    After publishing the package:

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

    You can execute the migration using:

    php artisan migrate

    Laravel automatically keeps track of which migrations have been executed and runs new ones accordingly.

    If you want to execute the migration from outside of the CLI, for example in a route, you can do so using the Artisan facade:

    Artisan::call('migrate')

    You can pass optional parameters such as force and path as an array to the second argument in Artisan::call.

    Further reading:

    • https://laravel.com/docs/5.1/artisan
    • https://laravel.com/docs/5.2/migrations#running-migrations
    0 讨论(0)
提交回复
热议问题