Home > OS >  Store top categories from an API request into the database
Store top categories from an API request into the database

Time:05-17

I have an API request like this:

$postInformation = 
(new postInformation)->handle(['field' => 'slug', 'value' => $this->slug]);

A dump of this response, besides other things, show some categories that are coming from this API request. And they are on this format where there is a 'categories' key with the top categories:

categories:
^ array:40 [
  "id" => 2
  ...
  "categories" => array:2 [
    "data" => array:15 [
      0 => array:3 [
        "id" => 6
        "name" => array:1 [
          "en" => "General"
        ]
        "on_request" => 0
      ]
      1 => array:3 [
        "id" => 14
        "name" => array:1 [
          "en" => "Tuts"
        ]
        "on_request" => 0
      ]
      2 => array:3 [
        "id" => 3
        "name" => array:1 [
          "en" => "Laravel"
        ]
        "on_request" => 0
      ]
      
      ...
  ]
  ...
 ]

I created a table 'post_top_categories' and a model PostTopCategory and I want to get the top categories from the API response above and store them into the 'post_top_categories' table. But I'm not understanding how to properly achieve this. Do you know how it can be achieved it? Thanks

CodePudding user response:

foreach($yourArray['categories']['data'] as $topCategory)
{
    $catId = $topCategory['id'];
    $catname = $topCategory['name']['en'];
    $catOnRequest = $topCategory['on_request'];
    // Do what you want with those values now
}
  • Related