laravel 如何在“php artisan migrate”之后触发事件?

0yycz8jy  于 2023-08-08  发布在  PHP
关注(0)|答案(2)|浏览(100)

我想在完成文件迁移后立即触发一个事件,因为我想在表中添加一个额外的列。在该列中,我想复制另一列的所有数据。
Is there any way to check if migrations are ended
这是与体面的答案,但我不能理解不够的链接。

忽略这个

if ($userData['grant_type'] == 'refresh_token') {
            $validator = Validator::make($userData, Config::get('boilerplate.refresh_token.validation_rules'));
        } elseif ($userData['grant_type'] == 'password') {
            $validator = Validator::make($userData, Config::get('boilerplate.login.validation_rules'));
        }

字符串

cbjzeqam

cbjzeqam1#

下面是使用数据库事件MigrationsEnded的最简单方法。
首先,创建一个新的服务提供者类,例如:
php artisan make:provider CommandListenerProvider
然后,将其添加到新提供程序,例如:

<?php

namespace App\Providers;

use Event;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Events\MigrationsEnded;

class CommandListenerProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        Event::listen(MigrationsEnded::class, function (MigrationsEnded $event) {
            
            // What will happen when a migration ends
            dump('You can set your logic here');
        });
    }
}

字符串
providers阵列内的config/app.php中注册您的提供程序。

'providers' => [
       ....
       App\Providers\CommandListenerProvider::class,
 ],


要测试它,只需运行php artisan migrate,您应该在dump()函数中获得相同的文本。终端/控制台中的"You can set your logic here"
然后,你就可以出发了!🎉

3yhwsihp

3yhwsihp2#

您应该创建一个侦听器,而不是像上面这样的服务提供程序。
你想监听MigrationsEnded事件,你可以像这样创建一个监听器。
然后您需要在EventServiceProvider.php中注册事件侦听器

<?php

namespace App\Listeners;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Database\Events\MigrationsEnded;

class MigrationsEndedListener
{
    /**
     * @param MigrationsEnded $migrationsEnded
     * @return void
     */
    public function handle(MigrationsEnded $migrationsEnded): void
    {
         // TODO Add Logic Here
    }
}

字符串

EventServiceProvider

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        MigrationsEnded::class => [
            MigrationsEndedListener::class
        ]
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
    }
}

相关问题