1

This is an example of a data list from Laravel DB:

Illuminate\Support\Collection Object
(
[items:protected] => Array
    (
        [0] => stdClass Object
            (
                [category] => Protections menstruelles
                [sub_category] => Sous-vêtements lavables
                [model] => Culotte menstruelle
            )

        [1] => stdClass Object
            (
                [category] => T-shirt, Top & Polo
                [sub_category] => Débardeur, Caraco
                [model] => Bustier
            )

        [2] => stdClass Object
            (
                [category] => Protections menstruelles
                [sub_category] => Sous-vêtements lavables
                [model] => Tanga menstruel
            )

        [3] => stdClass Object
            (
                [category] => Protections menstruelles
                [sub_category] => Sous-vêtements lavables
                [model] => Body menstruel
            )

        [4] => stdClass Object
            (
                [category] => Protections menstruelles
                [sub_category] => Maillot de bain menstruel
                [model] => 1 pièce
            )

        [5] => stdClass Object
            (
                [category] => Homewear
                [sub_category] => Chaussettes
                [model] => Socquettes
            )

        [6] => stdClass Object
            (
                [category] => Plage
                [sub_category] => Bas de maillot
                [model] => Short de bain
            )

        [7] => stdClass Object
            (
                [category] => Lingerie & Sous-vêtement
                [sub_category] => Soutien-gorge
                [model] => Triangle
            )

        [8] => stdClass Object
            (
                [category] => Lingerie & Sous-vêtement
                [sub_category] => Culotte, tanga & string
                [model] => Tanga
            )

        [9] => stdClass Object
            (
                [category] => Lingerie & Sous-vêtement
                [sub_category] => Culotte, tanga & string
                [model] => Culotte
            )

    )
)

And I would like to create a JSON object which could be like that:

        var subjectObject = {
          "Protections menstruelles": {
            "Maillot de bain menstruel": ["1 pièce"],
            "Sous-vêtements lavables": ["Body menstruel"]
          },
          "Lingerie & Sous-vêtement": {
            "Soutien-gorge": ["Triangle"],
            "Culotte, tanga & string": ["Tanga", "Culotte"]
          }
          ...
        }

The idea is to ask some questions in select and with JavaScript conditional the options according previous select. I want to use this tutorial for that: https://www.w3schools.com/howto/howto_js_cascading_dropdown.asp I need a help to construct the json input.

It's working with this laravel DB request :

->select('category','sub_category','model')
->whereNotNull('category')
->whereNotNull('sub_category')
->whereNotNull('model')
->distinct()
->get()
->groupBy('category')
->map(function($item){
    return collect($item)
        ->groupBy('sub_category')
        ->map(function($item){
            return collect($item)->pluck('model');
        })->toArray();
      })->toJson();

But i Can't use it in javascript :

var subjectObject = "{{ $collection }}";

It's not a json like in the example :

var subjectObject = {
 "Front-end": {
  "HTML": ["Links", "Images", "Tables", "Lists"],
  "CSS": ["Borders", "Margins", "Backgrounds", "Float"],
  "JavaScript": ["Variables", "Operators", "Functions", "Conditions"]    
 },
 "Back-end": {
   "PHP": ["Variables", "Strings", "Arrays"],
   "SQL": ["SELECT", "UPDATE", "DELETE"]
 }
}

1 Answer 1

1

It's a collection. You can use these methods :

  • groupBy method groups the collection's items by a given key
  • map method iterates through the collection and passes each value to the given callback
  • pluck method retrieves all of the values for a given key, and
  • toJson method converts the collection into a JSON serialized string
$collection
    ->groupBy('category')
    ->map(function($item){
        return collect($item)
            ->groupBy('sub_category')
            ->map(function($item){
                return collect($item)->pluck('model');
            })
            ->toArray();
    })
    ->toJson();

Output :

{
  "Protections menstruelles": {
    "Sous-vêtements lavables": [
      "Culotte menstruelle",
      "Tanga menstruel",
      "Body menstruel"
    ],
    "Maillot de bain menstruel": [
      "1 pièce"
    ]
  },
  "T-shirt, Top & Polo": {
    "Débardeur, Caraco": [
      "Bustier"
    ]
  },
  "Homewear": {
    "Chaussettes": [
      "Socquettes"
    ]
  },
  "Plage": {
    "Bas de maillot": [
      "Short de bain"
    ]
  },
  "Lingerie & Sous-vêtement": {
    "Soutien-gorge": [
      "Triangle"
    ],
    "Culotte, tanga & string": [
      "Tanga",
      "Culotte"
    ]
  }
}
Sign up to request clarification or add additional context in comments.

14 Comments

I have a last problem in this case, it's impossible to have data in json, I get only a string. Do you have any idea?
What do you mean? It's json, since you use ->toJson(). Or you want to json response like API?
I mean, the toJson give me string and not json... Then in javascript I can't use it as a json like this example : w3schools.com/howto/howto_js_cascading_dropdown.asp
You can use {{ $collection }} from your blade view (js section)
I did that yes : var subjectObject = "{{ $collection }}"; console.log(subjectObject); It gives me : {"Protections menstruelles":{"Sous-vêtements lavables":["Culotte menstruelle","Tanga menstruel","Body menstruel"],"Maillot de bain menstruel":["1 pièce"]},"T-shirt, Top & Polo":{"Débardeur, Caraco":["Bustier"]},&qu........a & string":["Tanga","Culotte"]}} Not a json like in the example
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.