Ad

Laravel Nova - Scope Relationship Fields

- 1 answer

Is there a way of adding a scope to the BelongsToMany fields, such that when you attach related models you can only do so from restricted options?

Example:

Post belongsToMany Tags (using Spatie/Laravel-Tags). Tags belongsToMany Posts.

Tags model has id, name, slug, type and timestamp properties.

On the Detail or Update views, I would like to be able to attach Tags to Post.

Using the default BelongsToMany field (or a third-party package) on the Post resource allows for me to add Tags to Post.

App\Nova\Post.php

public function fields(Request $request)
{
            BelongsToMany::make('Tags'),
}

However, I would like to only be able to add Tags where type = 'Books' to this model.

Ad

Answer

If you're using the Spatie Tags package, I'd suggest using their Nova Tags package. Then you can add the following to your field definitions:

Tags::make('Tags')->type('books'),

This will limit the available tags for that resource to those of type books. See the entry on the Nova Tags package and the base Spatie Tags package

Ad
source: stackoverflow.com
Ad