$user->categories()->sync(Category::whereIn('name', $request->get('categoriesselected'))->pluck('id'));
This should probably work :)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
I'm stuck on how to convert ['Category two', 'Category three'] to [2, 3] in the controller.
I have a User and Category models with a many-to-many relationship:
My categories table has 3 categories:
id: 1, name: 'Category one' id: 2, name: 'Category two' id: 3, name: 'Category three'
My category_user table looks like:
Schema::create('category_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('category_id');
$table->timestamps();
});
In my blade template, I have a multi-select dropdown which the user can select categories from to which the user belongs. I then post the categories selected to my controller as an array of strings. I'm using Vuetify which uses strings rather than integer values in its multi-select component.
If the user selects categories 2 and 3, the array posted to the controller is:
['Category two', 'Category three']
I'd like to use sync() to update the categories associated with the user like so:
public function update_user_categories(Request $request)
{
$user = auth()->user();
$user->categories()->sync($request->get('categoriesselected'));
$user->save();
return response()->json(null, 200);
}
How do I convert $request->get('categoriesselected') into an array of integers that corresponds to category_id? I.e. convert
['Category two', 'Category three']
to
[ 2, 3 ]
Sorry if this is obvious...I'm still quite new to Laravel and PHP.
$user->categories()->sync(Category::whereIn('name', $request->get('categoriesselected'))->pluck('id'));
This should probably work :)
Please or to participate in this conversation.