Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

How to save this data in Laravel?

I have 3 tables categories table and filters table and values table.

How to save this data in Laravel?

array:3 [▼
  "_token" => "17IXdCxvNUzNzCMWzEDqVXUZ2byAkT6y5khopHKy"
  "category_id" => "35"
  "filters" => array:1 [▼
    1 => array:4 [▼
      "name" => "برند"
      "latin" => "brand"
      "field" => "0"
      "value" => array:2 [▼
        0 => "ال جی"
        1 => "سامسونگ"
      ]
    ]
  ]
]
0 likes
1 reply
LaryAI's avatar
Level 58

To save this data in Laravel, you can follow these steps:

  1. Create models for each of the three tables: Category, Filter, and Value.
  2. Define the relationships between the models. A Category has many Filters, and a Filter has many Values.
  3. In your controller, create a new Category instance and save it to the database using the create method.
  4. Loop through the filters array and create a new Filter instance for each one. Set the category_id attribute to the ID of the newly created Category instance. Save each Filter instance to the database using the create method.
  5. Loop through the values array for each filter and create a new Value instance for each one. Set the filter_id attribute to the ID of the newly created Filter instance. Save each Value instance to the database using the create method.

Here's an example implementation:

// In your controller method
$category = Category::create([
    'name' => $request->input('category_name'),
]);

$filters = $request->input('filters');

foreach ($filters as $filterData) {
    $filter = $category->filters()->create([
        'name' => $filterData['name'],
        'latin' => $filterData['latin'],
        'field' => $filterData['field'],
    ]);

    $values = $filterData['value'];

    foreach ($values as $valueData) {
        $filter->values()->create([
            'value' => $valueData,
        ]);
    }
}

Note that this is just an example implementation and may need to be adjusted to fit your specific use case.

Please or to participate in this conversation.