php - AppServiceProvider 启动功能和动态标题
问题描述
我将变量传递给 AppServiceProvider boot() 中的所有视图 我将数据库中第一个用户的名称存储在此变量中,因此我可以将其作为标题放在我的布局中
当数据库(新数据库)中没有用户时,问题就会发生
开机()
public function boot()
{
Schema::defaultStringLength(191);
View::composer('*',function($view){
$title = DB::table('users')->first();
$view->with('title',$title);
});
我试过这个作为逻辑,但没有奏效
public function boot()
{
Schema::defaultStringLength(191);
$check = DB::table('users')->first();
if ($check != null) {
View::composer('*',function($view){
$title = DB::table('users')->first();
$view->with('title',$title); });
}else {
return view('nouser');
}
没有语法错误,但我认为问题是每次网站重新加载时都会呈现所有布局(我有 3 个)来宾和管理员都有
<title>{{$title->name}}</title>
和标题不是动态的应用程序和我编码的nouser页面我扩展了应用程序布局bcs它没有这个未定义的变量
问题是我需要向用户隐藏这个异常并将他重定向到说请注册的页面,然后我在注册后将他重定向到主页
解决方案
您的代码的主要问题是;如果没有用户,您将尝试在对象中打印某些内容。在尝试实现某些东西时,您应该注意SOLID原则。
$countUsers = DB::table('users')->count();
$title = null;
if($countUsers > 0){
$title = DB::table('users')->first()->name;
}
View::composer('*',function($view){
$view->with('title',$title);
});
if($countUsers == 0 ){
return view('nouser');
}
并在您的模板中使用
<title>{{$title}}</title>
代替
<title>{{$title->name}}</title>
使用View::composer
不是动态更改标题的更好解决方案。因此,您可以使用artesaos/seotools包来获取动态标题、描述等等。此外,它还具有动态 twitter 和 opengraph 元生成功能,这对 seo 非常重要。
<?php
....
class ForExampleController extends {
public function viewUser($ID){
$user = User::findOrFail($ID);
SEO::setTitle($user->name);
SEO::setDescription("This is the profile of ".$user->name);
SEO::opengraph()->setUrl(...); // you can set users profile url
// and much more..
}
}
?>
推荐阅读
- java - 单击关闭下拉菜单时如何查找元素定位器
- c# - 不了解 wpf 更新动态创建的图像控件可见性每秒变化的行为
- javascript - 使用 .reduce 对每个名称求和
- firebase - Firestore 安全规则:无法检查子集合中的文档是否等于用户 UID
- python - 如何合并具有相同索引的两个文件中的字符串?
- c# - 在 Unity 中无意中破坏了 BoxCollider
- javascript - 如何使用 .join .slice 或 .push 使这个加密器/解密器工作?
- php - 的程序含义?与否?
- ruby-on-rails - 如何通过单个控制器创建具有两个模型的两个记录(多步骤形式)
- python-2.7 - 仅当平台为 Windows 时才安装 python 依赖项