laravel - 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))
解决方案
不要在里面添加参数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 错误
推荐阅读
- c# - 如何编写高性能的 linq lambda 以避免低性能的 sql 查询?
- java - 如何配置 smarteist/Android-Image-Slider?
- python - 如何安装旧版本的pytorch
- installshield-2018 - 如何在 Installshield 2018 中将语言 ID 写入注册表?
- java - 无法在 java Spring Boot 中创建新实体。获取```无法启动嵌入式容器```错误
- teradata - 我有一个关于 Teradata 查询实施的问题
- continuous-integration - 如果依赖失败,则构建失败
- javascript - 带有多个和异步选项的 ui-select 问题
- asp.net-mvc - Tab 键不会移动到部分视图中的下一个文本框
- r - ggsurvplot:grDevices::col2rgb 中的错误(颜色,真)