Skip to content
Advertisement

Return all table’s rows in a Select field laravel Nova

I would like to return to my select all the elements of my ‘categories’ table except the current line. I didn’t find anything about this on the internet, so I’m coming to you.

My current item for Select:

Select::make('Parent Category')
                ->options([

            ])
                ->displayUsingLabels(),

And this is the head of my categories table:

Categories table

Advertisement

Answer

I understand you have a self referrencing relationship between the Category model, and itself such as

class Category extends Model
{

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }
}

In Nova usually, you would express the relationship between the Child and its Parent not as a Select field, but as a BelongsTo such as:

    BelongsTo::make('Parent Category', 'parent', Category::class)->searchable()->nullable(),

But you could use the Select field to have a pre-loaded array of Categories so you can filter out the current category onlyOnForms().

You can do it this way:

 public function fields(Request $request)
 {
     
        $fields = [
            
            // [ All your fields ]
            
            // We'll use a Select but onlyOnForms to show all categories but current category when in Forms
            Select::make('Parent', 'parent_id')->options(Category::where('id', '!=', request()->resourceId)->pluck('name', 'id'))->onlyOnForms(),

            // Use a BelongsTo to show the parent category when in Details page
            BelongsTo::make('Parent', 'parent', Category::class)->searchable()->nullable()->showOnDetail()->hideWhenCreating()->hideWhenUpdating(),
       
        ];


}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement