php - How to attach with loop in laravel?
Please help, so I want to use foreach to loop and attach data to the database using Eloquent in my Controller, I passed this is the parsed data as an array:
array:4 [?�?
"_token" => "NuO5J3nYPq9WBXVFd5rWHggdWOCWU8lvidNbLAM1"
"category_id" => "37"
"filters" => array:3 [?�?
1 => array:4 [?�?
"name" => "Brand"
"latin" => "brand"
"field" => "0"
"value" => array:3 [?�?
0 => "Apple"
1 => "LG"
2 => "Sumsung"
]
]
5 => array:4 [?�?
"name" => "Number of sim card"
"latin" => "number-of-sim-card"
"field" => "0"
"value" => array:3 [?�?
0 => "One"
1 => "Two"
2 => "Three"
]
]
9 => array:3 [?�?
"name" => "Color"
"latin" => "color"
"field" => "1"
]
]
"color_id" => array:3 [?�?
0 => "1"
1 => "6"
2 => "3"
]
]
And I want to loop (foreach) and save it to tables using attach() so it can be saved with the same ID in one time like this:
color_id | filter_id
I do not want this I want to see this in the database.
{-code-3}
I saved three colors so three rows should be displayed but this is 9.
This is the piece of blade:
{-code-4}
I'm using name="color[]" in the markup properties
And currently, I'm using this method for looping :
{-code-5}
Answer
Answer
------
1 | 1
1 | 2
1 | 3
3 | 1
3 | 2
3 | 3
6 | 1
6 | 2
6 | 3
Answer
Answer
------|||color_id | filter_id
Answer
Answer
------
1 | 1
2 | 1
3 | 1
Answer
Answer
------|||<script>
let count = 0;
$('#addFilter').click(function () {
count++;
'<label for="name">Name</label>'+
'<input type="text" id="name" class="form-control" name="filters['+count+'][name]">'+
'<label for="latin">Latin</label>'+
'<input type="text" id="latin" class="form-control" name="filters['+count+'][latin]">'+
'<label for="field">Field</label>'+
'<select id="field" class="form-select field" name="filters['+count+'][field]">'+
'<option value="0">Value</option>'+
'<option value="1">Color</option>'+
'</select>'+
'<label for="value">Value</label>' +
'<input type="text" id="value" class="form-control" name="filters['+groupId+'][value][]">' +
'<label for="color_id">Coor</label>' +
'<select class="form-control selectpicker" id="color_id" name="color_id[]" data-live-search="true">' +
'@foreach($colors as $color)'+
'<option value="{{ $color->id }}" data-content="<span class='+"'badge'"+' style='+"'background-color: {{ $color->color_code }}'"+'>{{ $color->color_name }}</span>">'+
'{{ $color->color_name }}' +
'</option>'+
'@endforeach'+
'</select>' +
}
</script>|||public function store(Request $request)
{
$filters = collect($request->filters);
$filters->each(function ($item) use ($request) {
if (isset($item['name']) && isset($item['latin'])) {
$filter = Filter::create([
'category_id' => $request->category_id,
'name' => $item['name'],
'latin' => $item['latin'],
'field' => $item['field'],
]);
} else {
return;
}
$filter->colors()->attach($request->color_id);
});
}
Source