Laravel Nova Documentation

website·Indexed 18 days ago

https://nova.laravel.com/docs

Official documentation for Laravel Nova v5, an administration panel for Laravel applications. Includes guides on installation, resource management, defining actions, filters, lenses, and metrics, as well as extensive customization options for fields, cards, dashboards, and tools.

Tokens
46.8K
Snippets
342
Records
366
Agent score
98%

What's inside Laravel Nova

  1. Customize Laravel Nova generation stubs

    v5

    Laravel Nova uses stub files to generate the boilerplate code for resources, actions, filters, lenses, and metrics. To apply common modifications automatically to these generated files, you can publish the default Nova stubs to your application and modify them.

    Running the publish command copies the stub files into the ./stubs/nova directory. If a specific stub file is deleted from this directory, Nova will revert to using its internal default version for that specific class.

    php artisan nova:stubs
  2. Use Static Actions for common tasks in Laravel Nova

    v5
    Laravel Nova provides static actions that allow you to perform common tasks without creating a dedicated action class. These are registered within the actions() method of a Nova resource.
    use Laravel
    ova\Actions\Action;
    use Laravel\Nova\Http\Requests\NovaRequest;
    use Laravel\Nova\Nova;
    
    public function actions(NovaRequest $request): array 
    {
        return [
            // Redirect to external URL
            Action::redirect('Visit Stripe Dashboard', 'https://stripe.com')->standalone(),
    
            // Visit internal Nova page
            Action::visit('View Logs', Nova::url('/logs'))->standalone(),
    
            // Display an error toast notification
            Action::danger('Disable User Account', 'This action is no longer available!'),
    
            // Open URL in a new browser tab
            Action::openInNewTab('Visit Stripe Dashboard', 'https://stripe.com')->standalone(),
    
            // Download a file from a URL
            Action::downloadUrl('Download Users Summaries', function () {
                return route('users.summaries');
            })->standalone(),
    
            // Display a custom Vue component modal
            Action::modal('Download User Summary', 'UserSummary', function ($user) {
                return [
                    'user_id' => $user->getKey(),
                ];
            })->sole(),
        ];
    }
  3. Enable Passkey authentication in Nova

    v5

    To enable Passkey authentication, you must update the User model, the NovaServiceProvider, and run migrations.

    1. Add Laravel\Fortify\PasskeyAuthenticatable trait and Laravel\Fortify\Contracts\PasskeyUser interface to the User model.
    2. Enable Features::passkeys() in the fortify method of App\Providers\NovaServiceProvider.
    3. Publish Fortify migrations and migrate the database.
    // User Model
    class User extends Authenticatable implements PasskeyUser
    {
        use Notifiable, PasskeyAuthenticatable;
    }
    
    // NovaServiceProvider.php
    protected function fortify(): void
    {
        Nova::fortify()
            ->features([
                Features::updatePasswords(),
                Features::passkeys(),
            ])
            ->register();
    }
    php artisan nova:publish
    php artisan migrate
  4. Create and define a Nova Lens

    v5

    Nova lenses allow you to fully customize the underlying Eloquent query for a resource, enabling complex joins and aggregate functions that standard filters cannot handle. Use the nova:lens Artisan command to generate a new lens class in app/Nova/Lenses.

    A lens is primarily defined by two methods:

    1. query: Builds the Eloquent query to retrieve data. It must return a Builder or Paginator.
    2. fields: Returns an array of Nova fields to display the retrieved data.

    Important: Always include the resource's ID in the selected columns of your query. If the ID is missing, Nova cannot display the "Select All Matching" option or the resource deletion menu.

    php artisan nova:lens MostValuableUsers
    namespace App
    
    use Laravel
    ova	tp
    equests
    LensRequest;
    use Laravel
    ova	tp
    equests
    NovaRequest;
    use Laravel
    ova
    Lenses
    Lens;
    use Illuminate
    Contracts
    Database
    Eloquent
    Builder;
    use Illuminate
    Contracts
    Pagination
    Paginator;
    use Laravel
    ova
    Fields
    ID;
    use Laravel
    ova
    Fields
    Text;
    
    class MostValuableUsers extends Lens
    {
        public static function query(LensRequest $request, Builder $query): Builder|Paginator
        {
            return $request->withOrdering(
                $request->withFilters($query),
                fn ($query) => $query->orderBy('revenue', 'desc')
            );
        }
    
        public function fields(NovaRequest $request): array
        {
            return [
                ID::make('ID', 'id'),
                Text::make('Name', 'name'),
            ];
        }
    
        public function uriKey()
        {
            return 'most-profitable-users';
        }
    }
  5. Manage and compile Nova tool assets

    v5
    Nova tools use a single-file Vue component (resources/js/components/Tool.vue) and CSS (resources/css/tool.css). Assets are compiled using the provided webpack.mix.js file via NPM commands.
    # Local development
    npm run dev
    
    # Production build (minify)
    npm run prod
    
    # Auto-compile on change
    npm run watch
  6. Disable Nova's theme switcher

    v5
    To hide the light/dark mode toggle and force Nova to follow the system preference, call Nova::withoutThemeSwitcher() in the boot method of the App\Providers\NovaServiceProvider class.
    // app/Providers/NovaServiceProvider.php
    
    public function boot(): void
    {
        parent::boot();
    
        Nova::withoutThemeSwitcher();
    }
  7. Check Laravel Nova system requirements

    v5

    Before installing Laravel Nova, ensure your environment meets the following minimum requirements:

    • Composer 2
    • Laravel Framework 10.x, 11.x, 12.x, or 13.x
    • Inertia.js 2.x
    • Laravel Mix 6.x
    • Node.js (Version 18.x+)
    • NPM 9.x

    Nova supports modern versions of Apple Safari, Google Chrome, Microsoft Edge, and Mozilla Firefox.

  8. Transform a Value Metric result

    v5
    Use the transform helper on a ValueResult to modify the calculated value before it is displayed to the user. This is useful for unit conversions, such as converting cents to dollars.
    use App\Models\Invoice;
    use Laravel\Nova\Http\Requests\NovaRequest;
    use Laravel\Nova\Metrics\ValueResult;
    
    public function calculate(NovaRequest $request): ValueResult
    {
        return $this->sum($request, Invoice::class, 'amount')
            ->transform(fn($value) => $value / 100);
    }
  9. Authorize relationship interactions in Nova

    v5

    Nova uses naming conventions to authorize relationship actions within the parent model's policy:

    1. Adding models: Use add{Model} (e.g., addComment on PodcastPolicy).
    2. Many-to-Many Attaching/Detaching: Use attach{Model} and detach{Model} (e.g., attachTag and detachTag on PodcastPolicy).
    3. Global Attach Permission: Use attachAny{Model} to determine if the "Attach" button should be displayed in the UI at all.
    // Authorize attaching a specific tag
    public function attachTag(User $user, Podcast $podcast, Tag $tag)
    {
        return true;
    }
    
    // Authorize if the user can attach ANY tag (controls UI visibility)
    public function attachAnyTag(User $user, Podcast $podcast)
    {
        return false;
    }
  10. Use dynamic field methods for specific contexts

    v5

    Available context methods:

    • fieldsForIndex
    • fieldsForDetail
    • fieldsForInlineCreate
    • fieldsForCreate
    • fieldsForUpdate
    • fieldsForPreview
    /**
     * Get the fields displayed by the resource on detail page.
     */
    public function fieldsForDetail(NovaRequest $request): array
    {
        return [
            Text::make('Name', function () {
                return sprintf('%s %s', $this->first_name, $this->last_name);
            }),
            Text::make('Job Title'),
        ];
    }
  11. Filter relatable query results

    v5
    Use relatableQueryUsing to customize the Eloquent query used to fetch results for a searchable relationship. This can be used for static filtering or dynamic filtering based on other field values using dependsOn.
    BelongsTo::make('User')
        ->relatableQueryUsing(function (NovaRequest $request, Builder $query) {
            $query->whereIn('teams', ['editor', 'writer']);
        })
        ->dependsOn('topic', function (BelongsTo $field, NovaRequest $request, FormData $formData) {
            if ($formData->topic === 'laravel-nova') {
                $field->relatableQueryUsing(function (NovaRequest $request, Builder $query) {
                    $query->whereIn('email', ['taylor@laravel.com', 'david@laravel.com']);
                });
            }
        }),