从数据库结果到视图共享全局变量?

时间:2017-02-25 10:41:08

标签: php laravel laravel-5 continuous-integration

在我的页眉和页脚中是来自数据库的一些动态导航。所以我需要Laravel中每个站点上的数据库结果。

Laravel在Sharing Data With All Views下的文档是描述的方式。

所以我在AppServiceProvider下的boot()创建了查询:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $navigation = \App\Navigation::all();
        view()->share('navigation', $navigation);
    }

    // ...
}

它有效,但我每次测试失败时都会使用CI

> Illuminate\Foundation\ComposerScripts::postInstall
> [ -f /usr/bin/php71 ] && /usr/bin/php71 artisan optimize || php artisan optimize

[Illuminate\Database\QueryException]                                         
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'homestead.navigation' doesn't exist (SQL: select * from `navigation`)                                                                       

[Doctrine\DBAL\Driver\PDOException]                                          
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'homestead.navigation' doesn't exist                                                      

[PDOException]                                                               
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'homestead.navigation' doesn't exist

这是因为此时不会迁移表格......

所以我抓住了这样的例外:

try {
    $navigation = \App\Navigation::all();
} catch (\Illuminate\Database\QueryException $e) {
    $navigation = [];
}
view()->share('navigation', $navigation);

这是正确的方法还是有更好的方法将数据库结果共享给视图?

1 个答案:

答案 0 :(得分:1)

您有这个,因为您的数据库尚未迁移。

使用composer代替share,这样就可以在真正需要数据时调用闭包(或ViewComposer类),而不是在应用启动时调用。

请参阅文档here