skip to Main Content

image

image2

Now I have like this
image3
but I want have more categories
like this

How to select many category?

2

Answers


  1. Let’s say in your case, we need to define the category for every features. So feature can have many categories and inverse category can have many features. Thus, it will be a Many To Many relationships.

    To accomplish this we need to create 3 tables features, categories, and intermediate table feature_category. The feature_category table will have the feature_id and category_id column which connects both feature and category table and this intermediate table called the pivot table.

    Here are the table structures:

    features
        id - integer
        name - string
     
    categories
        id - integer
        name - string
     
    feature_category
        feature_id - integer
        category_id - integer
    

    => category

    id  name                 
    --  -------    
    1   Category 1
    2   Category 2
    3   Category 3
    4   Category 4 
    

    => features

    id  name                 
    --  -------    
    1   Feature 1
    2   Feature 2
    3   Feature 3
    4   Feature 4 
    

    => feature_category

    id  feature_id   category_id            
    --  -------        -------
    1      1              1
    2      2              2
    3      3              2
    4      3              3
    4      3              4
    

    ===============================

    Our feature_category table before sync() operation:

    id  feature_id   category_id            
    --  -------        -------
    1      1              1
    2      2              2
    3      2              3
    4      2              4
    5      3              2
    6      4              3
    

    Laravel Sync() example:

    <?php
     
        use AppModelsFeature;
     
        $user = Feature::find(2);
     
        // Want to keep only "Category 2" (Id 2) category
        $user->category()->sync([2]); 
    

    After performing the above operation, our feature_category table will look like below:

    id  feature_id   category_id            
    --  -------        -------
    1      1              1
    2      2              2
    5      3              2
    6      4              3
    

    Checkboxes or dropdowns can be used from the frontend to select multiple categories for features and sync() method can be used to update feature cards accordingly.

    Login or Signup to reply.
    • First you need to create new table feature_category with two fields :

       (same type of features.id)  feature_id 
       (same type of categories.id) category_id
      
    • Second create belongsToMany relationship directly in Voyager.

    Example :

    enter image description here

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