在我的页眉和页脚中是来自数据库的一些动态导航。所以我需要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);
这是正确的方法还是有更好的方法将数据库结果共享给视图?
答案 0 :(得分:1)