首页 > 解决方案 > AppServiceProvider 中的单例导致新迁移出错

问题描述

我在其中注册了一个单身人士,AppServiceProvider它加载了一个货币模型。

问题似乎是,如果您在空数据库上运行迁移,它会在迁移完成之前尝试加载此货币模型。(因此尚不存在货币表或货币行)。

在尝试加载此单例之前,如何让货币迁移首先运行?

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Breadcrumbs::class, function($app){
            return new Breadcrumbs();
        });

        $this->app->singleton(Currency::class, function($app){
            return Currency::current();
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(Breadcrumbs $breadcrumbs, Currency $currency)
    {
        View::composer(['partials.*'], function($view) use ($breadcrumbs){
            $view->with('breadcrumbs', $breadcrumbs);
        });

        View::composer('*', function($view) use ($currency){
            $view->with([
                'me'        => Auth::user(),
                'currency'  => $currency
            ]);
        });
    }
}

并且迁移失败,并且:

  TypeError 

  Argument 2 passed to App\Providers\AppServiceProvider::boot() must be an instance of App\Models\Currency, null given, called in /home/vagrant/reviewmarket/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php on line 36

  at app/Providers/AppServiceProvider.php:34
     30▕      * Bootstrap any application services.
     31▕      *
     32▕      * @return void
     33▕      */
  ➜  34▕     public function boot(Breadcrumbs $breadcrumbs, Currency $currency)
     35▕     {
     36▕         View::composer(['partials.*'], function($view) use ($breadcrumbs){
     37▕             $view->with('breadcrumbs', $breadcrumbs);
     38▕         });

      +7 vendor frames 
  8   [internal]:0
      Illuminate\Foundation\Application::Illuminate\Foundation\{closure}(Object(App\Providers\AppServiceProvider))

      +5 vendor frames 
  14  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

标签: laravellaravel-8

解决方案


不要在里面添加参数boot()

public function boot()
{
    $breadcrumbs = Breadcrumbs::all();
    $currency = Currency::all();

    View::composer(['partials.*'], function ($view) use ($breadcrumbs) {
        $view->with('breadcrumbs', $breadcrumbs);
    });

    View::composer('*', function ($view) use ($currency) {
        $view->with([
            'me'        => Auth::user(),
            'currency'  => $currency
        ]);
    });
}

像这样修复

Laravel 在内部将其称为引导函数 App\Providers\AppServiceProvider::boot(),当您在引导方法中添加 2 个参数时,boot()函数必须发送 2 个参数,即 Couse 错误


推荐阅读