这是用户在 2024-5-30 13:48 为 https://nova.laravel.com/docs/resources/ 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?
logo

The Basics

Introduction  介绍

Laravel Nova is a beautiful administration dashboard for Laravel applications. Of course, the primary feature of Nova is the ability to administer your underlying database records using Eloquent. Nova accomplishes this by allowing you to define a Nova "resource" that corresponds to each Eloquent model in your application.
Laravel Nova 是 Laravel 应用程序的美丽管理仪表板。当然,Nova 的主要功能是使用 Eloquent 管理底层数据库记录的能力。Nova 通过允许您定义与应用程序中每个 Eloquent 模型对应的 Nova“资源”来实现这一点。

Defining Resources  定义资源

By default, Nova resources are stored in the app/Nova directory of your application. You may generate a new resource using the nova:resource Artisan command:
默认情况下,Nova 资源存储在您的应用程序的 app/Nova 目录中。您可以使用 nova:resource Artisan 命令生成新资源:

bash
php artisan nova:resource Post

The most basic and fundamental property of a resource is its model property. This property tells Nova which Eloquent model the resource corresponds to:
资源最基本和基本的属性是其 model 属性。此属性告诉 Nova 资源对应的 Eloquent 模型是哪个:

php
/**
 * The model the resource corresponds to.
 *
 * @var string
 */
public static $model = 'App\Models\Post';

Freshly created Nova resources only contain an ID field definition. Don't worry, we'll add more fields to our resource soon.
新创建的 Nova 资源只包含一个 ID 字段定义。别担心,我们很快会为我们的资源添加更多字段。

Reserved Resource Names 保留资源名称

Nova contains a few reserved words which may not be used for resource names:
Nova 包含一些保留字,不能用于资源名称:

  • Card 卡片
  • Dashboard 仪表盘
  • Field
  • Impersonate 冒充
  • Metric 公制
  • Resource 资源
  • Search 搜索
  • Script
  • Style
  • Tool 工具

Registering Resources  注册资源

Automatic Registration 自动注册

By default, all resources within the app/Nova directory will automatically be registered with Nova. You are not required to manually register them.
默认情况下, app/Nova 目录中的所有资源将自动注册到 Nova。您无需手动注册它们。

Before resources are available within your Nova dashboard, they must first be registered with Nova. Resources are typically registered in your application's app/Providers/NovaServiceProvider.php file. This file contains various configuration and bootstrapping code related to your Nova installation.
在您的 Nova 仪表板中可用资源之前,它们必须首先在 Nova 中注册。资源通常在您的应用程序的 app/Providers/NovaServiceProvider.php 文件中注册。该文件包含与您的 Nova 安装相关的各种配置和引导代码。

As mentioned above, you are not required to manually register your resources; however, if you choose to do so, you may do so by overriding the resources method of your NovaServiceProvider.

There are two approaches to manually registering resources. You may use the resourcesIn method to instruct Nova to register all Nova resources within a given directory. Alternatively, you may use the resources method to manually register individual resources:
有两种手动注册资源的方法。您可以使用 resourcesIn 方法指示 Nova 注册给定目录中的所有 Nova 资源。或者,您可以使用 resources 方法手动注册单个资源:

php
use App\Nova\User;
use App\Nova\Post;

/**
 * Register the application's Nova resources.
 *
 * @return void
 */
protected function resources()
{
    Nova::resourcesIn(app_path('Nova'));

    Nova::resources([
        User::class,
        Post::class,
    ]);
}

Once your resources are registered with Nova, they will be available in the Nova sidebar:
一旦您的资源在 Nova 中注册成功,它们将会在 Nova 侧边栏中可用:

Nova Dashboard

If you do not want a resource to appear in the sidebar, you may override the displayInNavigation property of your resource class:
如果您不希望某个资源出现在侧边栏中,您可以覆盖您资源类的 displayInNavigation 属性:

php
/**
 * Indicates if the resource should be displayed in the sidebar.
 *
 * @var bool
 */
public static $displayInNavigation = false;

Customizing Resource Menus
自定义资源菜单

You can customize the resource's menu by defining a menu method on your resource class:
您可以通过在资源类上定义 menu 方法来自定义资源菜单:

php
use Illuminate\Http\Request;

/**
 * Get the menu that should represent the resource.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Laravel\Nova\Menu\MenuItem
 */
public function menu(Request $request)
{
    return parent::menu($request)->withBadge(function () {
        return static::$model::count();
    });
}

Please refer to the documentation on menu customization for more information.

Grouping Resources  资源分组

If you would like to separate resources into different sidebar groups, you may override the group property of your resource class:

php
/**
 * The logical group associated with the resource.
 *
 * @var string
 */
public static $group = 'Admin';

Resource Table Style Customization
资源表格样式定制

Nova supports a few visual customization options for your resources.
Nova 支持为您的资源提供一些视觉定制选项。

Table Styles  表格样式

Sometimes it's convenient to show more data on your resource index tables. To accomplish this, you can use the "tight" table style option designed to increase the visual density of your table rows. To accomplish this, override the static $tableStyle property or the static tableStyle method on your resource class:
有时在资源索引表上显示更多数据是很方便的。为了实现这一点,您可以使用“tight”表格样式选项,旨在增加表格行的视觉密度。为了实现这一点,请覆盖您资源类上的静态 $tableStyle 属性或静态 tableStyle 方法:

php
/**
 * The visual style used for the table. Available options are 'tight' and 'default'.
 *
 * @var string
 */
public static $tableStyle = 'tight';

This will display your table rows with less visual height, enabling more data to be shown:

Tight Table Style

Column Borders

You can instruct Nova to display column borders by overriding the static $showColumnBorders property or the static showColumnBorders method on your resource class:

php
/**
 * Whether to show borders for each column on the X-axis.
 *
 * @var bool
 */
public static $showColumnBorders = true;

Setting this property to true will instruct Nova to display the table with borders on every table item:

Table Column Borders

Resource Table Click Action

By default, when clicking on a resource table row, Nova will navigate to the detail view for the resource. However, you may want Nova to navigate to the edit form instead. You can customize this behavior by changing the clickAction property on the resource's class:
默认情况下,单击资源表行时,Nova 将导航到资源的详细视图。但是,您可能希望 Nova 转而导航到编辑表单。您可以通过更改资源类上的 clickAction 属性来自定义此行为。

php
/**
 * The click action to use when clicking on the resource in the table.
 *
 * Can be one of: 'detail' (default), 'edit', 'select', 'preview', or 'ignore'.
 *
 * @var string
 */
public static $clickAction = 'edit';

Choosing the select option will select the resource row's checkbox. The ignore option instructs Nova to ignore click events altogether.

Eager Loading  急切加载

If you routinely need to access a resource's relationships within your fields, resource title, or resource subtitle, it may be a good idea to add the relationship to the with property of your resource. This property instructs Nova to always eager load the listed relationships when retrieving the resource.
如果您经常需要在字段、资源标题或资源副标题中访问资源的关系,那么将关系添加到资源的 with 属性可能是一个好主意。该属性指示 Nova 在检索资源时始终急切加载列出的关系。

For example, if you access a Post resource's user relationship within the Post resource's subtitle method, you should add the user relationship to the Post resource's with property:

php
/**
 * The relationships that should be eager loaded on index queries.
 *
 * @var array
 */
public static $with = ['user'];

Resource Replication  资源复制

Sometimes, you may want to create a new resource while using all of the data from an existing resource as a starting point. Nova's resource replication feature does just that. After clicking the replicate button, you'll be whisked away to a resource creation form with all of the replicated resource's data hydrated into the form and ready for tweaking:

Resource Replication

To customize the replication model, you can override the replicate method on the resource class:
要自定义复制模型,您可以在资源类上覆盖 replicate 方法:

php
/**
 * Return a replicated resource.
 *
 * @return static
 *
 * @throws \InvalidArgumentException
 */
public function replicate()
{
    return tap(parent::replicate(), function ($resource) {
        $model = $resource->model();

        $model->name = 'Duplicate of '.$model->name;
    });
}

Attachments May Not Be Replicated

Markdown and Trix fields that use the withFiles method may not be replicated.
MarkdownTrix 字段使用 withFiles 方法可能无法复制。

If you need to store a reference to the original resource's ID, you may access the fromResourceId value on the replication request. Typically, this value would be accessed from an event listener or observer that is listening for the model's creating event:
如果您需要存储对原始资源 ID 的引用,可以在复制请求上访问 fromResourceId 值。通常,此值将从侦听模型的 creating 事件的事件侦听器或观察者中访问:

php
namespace App\Observers;

use App\Models\Post;
use Laravel\Nova\Http\Requests\NovaRequest;
use Laravel\Nova\Nova;

class PostObserver
{
    /**
     * Handle the creation of a new Post.
     *
     * @param  \App\Models\Post  $model
     * @return void
     */
    public function creating(Post $model): void
    {
        Nova::whenServing(function (NovaRequest $request) use ($model) {
            $model->parent_id = $request->input('fromResourceId');
        });
    }
}

Resource Events  资源事件

All Nova operations use the typical save, delete, forceDelete, restore Eloquent methods you are familiar with. Therefore, it is easy to listen for model events triggered by Nova and react to them. The easiest approach is to simply attach a Laravel model observer to a model:

php
namespace App\Providers;

use App\Models\User;
use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        User::observe(UserObserver::class);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

If you would like to attach an observer whose methods are invoked only during Nova related HTTP requests, you may register observers using the make method provided by the Laravel\Nova\Observable class. Typically, this should be done within your application's NovaServiceProvider:

php
use App\Models\User;
use Laravel\Nova\Observable;
use App\Observers\UserObserver;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    parent::boot();

    Observable::make(User::class, UserObserver::class);
}

Alternatively, you can determine if the current HTTP request is serving a Nova related request within the Observer itself using Nova's whenServing method:

php
namespace App\Observers;

use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Nova\Http\Requests\NovaRequest;
use Laravel\Nova\Nova;

class UserObserver
{
    /**
     * Handle the User "created" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function created(User $user)
    {
        Nova::whenServing(function (NovaRequest $request) use ($user) {
            // Only invoked during Nova requests...
        }, function (Request $request) use ($user) {
            // Invoked for non-Nova requests...
        });

        // Always invoked...
    }
}

Resource Hooks

Nova also allows you to define the following static methods on a resource to serve as hooks that are only invoked when the corresponding resource action is executed from within Laravel Nova:

  • afterCreate
  • afterUpdate
  • afterDelete
  • afterForceDelete
  • afterRestore

For example, you may want to send an email verification notification after a user has been created within Nova:

php
use App\Models\User;
use App\Nova\Resource;
use Illuminate\Database\Eloquent\Model;
use Laravel\Nova\Http\Requests\NovaRequest;

class User extends Resource
{
    /**
     * Register a callback to be called after the resource is created.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public static function afterCreate(NovaRequest $request, Model $model)
    {
        $model->sendEmailVerificationNotification();
    }
}

Preventing Conflicts

If a model has been updated since it was last retrieved by Nova, Nova will automatically respond with a 409 Conflict HTTP status code and display an error message to prevent unintentional model changes. This may occur if another user updates the model after you have opened the "Edit" page on the resource. This feature is also known as the Nova "Traffic Cop".

Disabling Traffic Cop

If you are not concerned with preventing conflicts, you can disable the Traffic Cop feature by setting the trafficCop property to false on a given resource class:

php
/**
 * Indicates whether Nova should check for modifications between viewing and updating a resource.
 *
 * @var bool
 */
public static $trafficCop = false;

You may also override the trafficCop method on the resource if you have more intense customization needs in order to determine if this feature should be enabled:

php
/**
 * Indicates whether Nova should check for modifications between viewing and updating a resource.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return  bool
*/
public static function trafficCop(Request $request)
{
    return static::$trafficCop;
}

Time Synchronization

If you are experiencing issues with traffic cop you should ensure that your system time is correctly synchronized using NTP.

Resource Polling

Nova can automatically fetch the latest records for a resource at a specified interval. To enable polling, override the polling property of your Resource class:

php
/**
 * Indicates whether the resource should automatically poll for new resources.
 *
 * @var bool
 */
public static $polling = true;

To customize the polling interval, you may override the pollingInterval property on your resource class with the number of seconds Nova should wait before fetching new resource records:

php
/**
 * The interval at which Nova should poll for new resources.
 *
 * @var int
 */
public static $pollingInterval = 5;

Toggling Resource Polling

By default, when resource polling is enabled, there is no way to disable it once the page loads. You can instruct Nova to display a start / stop toggle button for resource polling by setting the showPollingToggle property on your resource class to true:

php
/**
 * Indicates whether to show the polling toggle button inside Nova.
 *
 * @var bool
 */
public static $showPollingToggle = true;

Nova will then display a clickable button that you may use to enable / disable polling for the resource:

Nova Resource Polling Toggle Button

Redirection

Nova allows you to easily customize where a user is redirected after performing resource actions such as creating or updating a resource:

Behind the scenes, Nova's redirect features use Inertia.js's visit method. Because of this, redirection is limited to paths within Laravel Nova. You may invoke the URL::remote method to redirect to an external URL:

php
use Laravel\Nova\URL;

return URL::remote('https://nova.laravel.com');

After Creating Redirection

You may customize where a user is redirected after creating a resource using by overriding your resource's redirectAfterCreate method:

php
/**
 * Return the location to redirect the user after creation.
 *
 * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
 * @param  \Laravel\Nova\Resource  $resource
 * @return \Laravel\Nova\URL|string
 */
public static function redirectAfterCreate(NovaRequest $request, $resource)
{
    return '/resources/'.static::uriKey().'/'.$resource->getKey();
}

After Updating Redirection

You may customize where a user is redirected after updating a resource using by overriding your resource's redirectAfterUpdate method:

php
/**
 * Return the location to redirect the user after update.
 *
 * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
 * @param  \Laravel\Nova\Resource  $resource
 * @return \Laravel\Nova\URL|string
 */
public static function redirectAfterUpdate(NovaRequest $request, $resource)
{
    return '/resources/'.static::uriKey().'/'.$resource->getKey();
}

After Deletion Redirection

You may customize where a user is redirected after deleting a resource using by overriding your resource's redirectAfterDelete method:

php
/**
 * Return the location to redirect the user after deletion.
 *
 * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
 * @return \Laravel\Nova\URL|string|null
 */
public static function redirectAfterDelete(NovaRequest $request)
{
    return null;
}

Pagination

Nova has the ability to show pagination links for your Resource listings. You can choose between three different styles: "simple", "load-more", and "links", depending on your application's needs:

Simple Pagination

Load-more Pagination

Links Pagination

By default, Nova Resources are displayed using the "simple" style. However, you may customize this to use either the load-more or links styles by changing the value of the pagination configuration option within your application's config/nova.php configuration file:

php
'pagination' => 'links',

Customizing Pagination

If you would like to customize the selectable maximum result amounts shown on each resource's "per page" filter menu, you can do so by customizing the resource's perPageOptions property:

php
/**
 * The pagination per-page options configured for this resource.
 *
 * @return array
 */
public static $perPageOptions = [50, 100, 150];

Alternatively, you can override the perPageOptions method on your application's base Resource class, which is created when you install Nova:

php
/**
 * The pagination per-page options configured for this resource.
 *
 * @return array
 */
public static function perPageOptions()
{
    return [50, 100, 150];
}

Customizing perPageOptions & Resource Fetching

Changing the value of perPageOptions on your Resource will cause Nova to fetch the number of resources equal to the first value in the perPageOptions array.

Using the $perPageViaRelationship property, you may also customize the number of resources displayed when a particular resource is displayed on another resource's detail view as a relationship:

php
/**
 * The number of resources to show per page via relationships.
 *
 * @var int
 */
public static $perPageViaRelationship = 10;

CSV Export

Occasionally you may need to export a group of resource records as a CSV file so that you can interact with the data in a spreadsheet application or import the data into another system. Thankfully, Nova includes built-in support for exporting resource data.

To get started, add the Laravel\Nova\Actions\ExportAsCsv action to your Nova resource:

php
use Laravel\Nova\Actions\ExportAsCsv;
use Laravel\Nova\Http\Requests\NovaRequest;

/**
 * Get the actions available for the resource.
 *
 * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
 * @return array
 */
public function actions(NovaRequest $request)
{
    return [
        ExportAsCsv::make(),
    ];
}

If you would like to allow the user to name the CSV file that is downloaded, you may invoke the nameable method when registering the action:

php
return [
    ExportAsCsv::make()->nameable(),
];

If you would like to customize and format the fields that are included in the generated CSV, you may invoke the withFormat method when registering the action:

php
return [
    ExportAsCsv::make()->withFormat(function ($model) {
        return [
            'ID' => $model->getKey(),
            'Name' => $model->name,
            'Email Address' => $model->email,
        ];
    }),
];

Resource Index Search Debounce

You may wish to customize the search debounce timing of an individual resource's index listing. For example, the queries executed to retrieve some resources may take longer than others. You can customize an individual resource's search debounce by setting the debounce property on the resource class:

php
/**
 * The debounce amount (in seconds) to use when searching this resource.
 *
 * @var float
 */
public static $debounce = 0.5; // 0.5 seconds

Keyboard Shortcuts

You may press the C key on a resource index to navigate to the "Create Resource" page. On the resource detail page, the E key may be used to navigate to the "Update Resource" page.