skip to Main Content

This is a classic, but I’m using the amazing SPLADE from slade.dev, and can’t get it to work. (How is SPLADE not a tag on stackoverflow yet?)

Use case: The user selects a main category, and then only the sub-categories of that category must show in the sub-categories for him to select from.

In the controller:

 $categories = Category::whereNull('parent_id')->orderBy('name')->pluck('name', 'id');

In the blade:

<x-splade-select :options="$categories" label="Category" name="category_id" />
                <x-splade-select :options="$subcategories" label="Sub-category" name="subcategory_id" remote-url="/getSubcategories/${form.categoryId}" />

getSubcategories is an API that retrieves the subcategories for a given $category_id:

$subcategories = Category::whereNotNull('parent_id')->where('parent_id', $category_id)->pluck('name', 'id'); 

${form.categoryId} in the blade above is not right. How do I retrieve the current form’s category_id to send to the API?

2

Answers


  1. Chosen as BEST ANSWER

    Solved it:

    In blade:

     <x-splade-select :options="$categories" label="Category:" name="category_id" />
     <x-splade-select label="Sub-category" name="subcategory_id" remote-url="`/api/getSubcategories/${form.category_id}`" select-first-remote-option />
    

    Where $categories is passed from the controller:

     $categories = Category::whereNull('parent_id')->where('active', 1)->orderBy('name')->pluck('name', 'id');
    

    and the api returns $subcategories as follows:

     public function getSubcategories(int $category_id = NULL) //Request $request
        {
            $subcategories = NULL;
    
            if ($category_id) {
                $subcategories = Category::whereNotNull('parent_id')
                    ->where('parent_id', $category_id)
                    ->where('active', 1)
                    // ->orderBy('name') //pluck ignores it anyway
                    ->pluck('name', 'id');
            } else {
                $subcategories = Category::whereNotNull('parent_id')
                    ->where('active', 1)
                    // ->orderBy('name') //pluck ignores it anyway
                    ->pluck('name', 'id');
            }
    
            return $subcategories;
        }
    

  2. I used to deal with this for my project as well.
    My solution:

    • Get all main category
    • Get all sub category (add class attribute into sub category html)
    • Create js handle main category option:selected to show/hide sub category by class name.

    Note: For litle category 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search