Laravel Voyager - two dropdown "Category" and "Subcategory"

3.4k views Asked by At

I am using Laravel Voyager admin panel.

I have a 'products' table where PRODUCT has parent SUBCATEGORY and CATEGORY. I have also made these relationships: 'product-subcategory' and 'product-category'.

Screenshot

So, when I want to add new product, I can choose CATEGORY and SUBCATEGORY from dropdown.

The problem is, SUBCATEGORY dropdown shows all of the subcategories:

I want see the SUBCATEGORIES only from the CATEGORY I choose. (like we get the column names of specified MODEL(for referencing) when we create relationships in voyager)

The reason I want this is to prevent adding products under the wrong Category and Subcategory.

Is there a way to achieve this? Should I use some JSON in the 'Optional Details' field?

1

There are 1 answers

0
Mojtaba Hn On BEST ANSWER

Unfortunately what you want is not possible with default Voyager options. but It's not even necessary to do what you want this way.

Following method will make a single dropdown containing options like category - subcategory.

  1. the good way is to connect sub_categories to categories (using category_id on sub_categories) and then connect products to sub_categories ( using sub_category_id on products).

  2. then edit your SubCategory Model and change title value using Laravel accessors:

class Product{
   //stuff

   //change showing attribute value for BREAD
   public function getTitleAttribute(){
      return $this->category->title . ' - ' . $this->getOriginal('title');
   }

   // access original subcategory title
   public function getRealTitleAttirbute(){
      return $this->getOriginal('title');
   }
}

its done. just notice we can access subcategory's real value using $subcategory->real_title.

good luck