John Davidson

php - Laravel trying to store multi-data

0 comments
Message:


I'm trying to store multi-data to my pivot table. I have CategoryUser table with category_id and user_id.


Store function


public function store(Request $request)
{
foreach ($request->userId as $key => $userId) {
$data = new CategoryUser();
$data->user_id = $userId;
$data->category_id = $request->categoryId[$key];
$data->save();
}

return redirect()->back();
}

In my Blade file i have name="categoryId[]" and name="userId[]".
However, it stores only one category_id. What am I doing wrong?



My Answer:
input('categories') as $category_id) {
CategoryUser::create([
'category_id' => $category_id,
'user_id' => auth()->user()->id
]);
}

return redirect()->back()->with('success', 'Categories added successfully');
}

Rate this post

5 of 5 based on 8844 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us