gwd/seo-meta-nova-field

一个Laravel Nova字段,可以向资源添加所有SEO相关的元字段。


README

这个自定义nova字段,可以通过一个单独的特性在模型中添加SEO相关字段。

如何安装

要安装包,请运行以下安装命令

composer require gwd/seo-meta-nova-field

然后运行迁移

php artisan migrate

然后发布配置

php artisan vendor:publish --provider="Gwd\SeoMeta\FieldServiceProvider"

如何使用字段

找到您想要添加SEO字段的模式,例如可以是App\Models\Page,然后添加SeoMetaTrait特性

...
use Gwd\SeoMeta\Traits\SeoMetaTrait;

class Page extends Model
{
    use SeoMetaTrait;
    ...
}

然后在nova资源App\Nova\Page中使用该字段

...
use Gwd\SeoMeta\SeoMeta;

class Page extends Resource
{
  ...
  public function fields(Request $request)
  {
    return [
      ...,
      SeoMeta::make('SEO', 'seo_meta')
        ->disk('s3-public') //disk to store seo image, default is public
    ];
  }
}

然后进入布局blade文件顶部,默认为resources/views/welcome.blade.php

...
<head>
    @include('seo-meta::seo')
    ...
</head>

其中@include('seo-meta::seo', ['page' => $page])应该包含与SeoMetaTrait特性相关联的模型实例。

如果您当前页面没有选择任何模型/资源,则可以按如下方式获取页面的SEO数据

use Gwd\SeoMeta\Helper\Seo;
...
Route::get('/tester', function(){
    return view('page', [
        'seo' => Seo::renderAttributes('SEO title', 'SEO description', 'SEO keywords', 'SEO image', 'index, follow'), // Builds the seo array
    ]);
});

以下是如何查看Seo::renderAttributes静态方法

为模型设置默认值

如果SEO值每次都应该有相同的结构,则您可以通过特性中的以下方法设置它

// Return the SEO title for the model
public function getSeoTitleDefault(): string

// Return the SEO description for the model
public function getSeoDescriptionDefault(): string

// Return the SEO keywords for the model
public function getSeoKeywordsDefault(): string

// Return the SEO image for the model
public function getSeoImageDefault(): string

// Return the SEO follow type for the model
public function getSeoFollowDefault(): string

设置Sitemap功能

如果您想启用Sitemap功能,请将seo.sitemap_status配置更改为true。然后,将具有SeoSitemapTrait特性的模型添加到seo.sitemap_models数组中,如下所示

    ...
    'sitemap_status' => env('SITEMAP_STATUS', true),

    ...
    'sitemap_models' => [
        App\Models\Page::class
    ],

将Sitemap特性添加到模型中

当您想将eloquent模型显示在Sitemap中时,需要将其添加到SeoSitemapTrait特性中

...
use Gwd\SeoMeta\Traits\SeoSitemapTrait;

class Page extends Model
{
    use SeoMetaTrait, SeoSitemapTrait;
    ...

    /**
     * Get the Page url by item
     *
     * @return string
     */
    public function getSitemapItemUrl()
    {
        return url($this->slug);
    }

    /**
     * Query all the Page items which should be
     * part of the sitemap (crawlable for google).
     *
     * @return Builder
     */
    public static function getSitemapItems()
    {
        return static::all();
    }
}

现在您应该能够访问seo.sitemap_path,默认为/sitemap。然后,您应该得到一个符合正确Sitemap结构的XML,可用于Google搜索控制台

Laravel Nova中的外观

如果字段显示在资源的索引视图中,则您应该看到一个带点的列:alt text

详细视图中,如果没有设置SEO,您将看到一条提示“需要一些SEO数据”的文本。但是,如果您有SEO数据,则将获得一个切换按钮,该按钮将显示如何在Google和Facebook上显示:alt text alt text

表单视图中,您应该看到所有的SEO输入字段:alt text