mbrown1408's avatar

Laravel Nova BelongsTo Relationship

Hi all,

I'm just learning Nova and running into an issue with filtering relationship belongsto fields based off a parent value in select fields.

Structure is as follows:

category has many subcategories | subcategories belongsto category

category has many items (inventory items) | items belongsto category

items belongsto subcategories | subcategories has many items

the associated models have the relationships defined and everything works with foreign keys, however the subcategory select field shows all subcategories.how do I filter the subcategory select field to only show the subcategories based off the id of the value selected in the category field?

ex: category = overhead (id 1) subcategory select field should only return the title where 'category_id' = 1 on the subcategories table.

What I've tried:

        BelongsTo::Make('Subcategory'),

This works, however the list isn't filtered based off category value.

        Select::make('Subcategory')->options(\App\Models\Inventory\Subcategory::pluck('title')->where('category_id', '=', '2')),

This doesnt return any results, not sure what I did wrong, also not sure how to make it dynamic for the category value.

       BelongsTo::make('Subcategory')->resolveUsing(\App\Models\Inventory\Subcategory::pluck('title')->where('id', '=', '2')),

This doesnt return any results, not sure what I did wrong, also not sure how to make it dynamic for the category value.

0 likes
6 replies
mbrown1408's avatar

I couldn't get it to work on my own accord. I broke down and used this package: https://github.com/orlyapps/nova-belongsto-depend

I will look at their code and see how it's done and try to post a resolution for people that don't like using packages like myself.

Still open to tips and tricks if anybody has any ideas tho!

mbrown1408's avatar

I didn’t try it. I literally built my own custom fields with emit based off the above blog post. The belingsTo package for me wasn’t working with polymorphic and has many through relationships so I simply uninstalled it.

Please or to participate in this conversation.