首页 > 解决方案 > 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它没有这个未定义的变量

问题是我需要向用户隐藏这个异常并将他重定向到说请注册的页面,然后我在注册后将他重定向到主页

标签: phplaravelvariableslaravel-blade

解决方案


您的代码的主要问题是;如果没有用户,您将尝试在对象中打印某些内容。在尝试实现某些东西时,您应该注意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..
    }
}
?>

推荐阅读