I
I
Ilya Loopashko2021-04-12 12:11:47
Laravel
Ilya Loopashko, 2021-04-12 12:11:47

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

1 answer(s)
A
Alexey Ukolov, 2021-04-12
@deadloop

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);

Why are you calling the variable $categorieseven though it contains exactly one category found by ID?
Why are you loading category roles?
Why are you calling the variable $rolewhen it contains the array of roles you dumped above?
Why are you $categoriesworking 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 question

Ask a Question

731 491 924 answers to any question