Answer the question
In order to leave comments, you need to log in
How to arrange iteration (foreach) in the controller?
Kind everyone. I have a method, for category 1 roles 2,3,4 are assigned. How to properly arrange foreach when data will come like this (dynamic, from a form) ($roles = $request->category;):
array:3 [▼
1 => array:3 [▼
2 => "2"
3 => "3"
4 => "4"
]
2 => array:2 [▼
3 => "3"
4 => "4"
]
3 => array:2 [▼
1 => "1"
2 => "2"
]
]
public function update(Request $request) {
$categories = Category::with('roles')->find(1);
$categories->roles()->sync([2,3,4]);
return view('home');
}
Answer the question
In order to leave comments, you need to log in
You need to go back to the tutorial and learn to understand what's going on in your code, and not mindlessly rearrange the letters in the hope that something will work out.
As I do, but nothing works.
foreach($roles as $cat => $role) { $categories = Category::with('roles')->find($cat); $data[] = $role; } $categories->roles()->sync($data);
$categories
even though it contains exactly one category found by ID? $role
when it contains the array of roles you dumped above? $categories
working with a variable outside the loop in which it is created?foreach($request->category as $categoryId => $roles) {
Category::find($categoryId)->roles()->sync($roles);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question