'How can I link a checkbox based on a categories table to the user table? Laravel 7

I have a categories table which I use to create some checkboxes in the registration form. Now I would need to get those values and assign it to the user table. How can I do that? I've already created a pivot user_category table.

This is the form:

<div class="form-group">
            <label>Tipologia</label>
            @foreach($categories as $category)
                
                <div class="form-check">
                    <input class="form-check-input" name="categories[]" type="checkbox" value="{{$category->id }}">
                    <label class="form-check-label" for="{{$category->name}}">
                        {{$category->name}}
                    </label>
                </div>
    
            @endforeach
          </div>

And this is the registration controller:

protected function create(array $data)
{
    // modifica dati da creare. Aggiunti p_iva, address, business_name
    return User::create([
        'business_name' => $data['business_name'],
        'address' => $this->getAddress($data['street'], $data['civic'], $data['city'], $data['state'], $data['cap']),
        'p_iva' => $data['p_iva'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}
protected function getRegisterForm()
{
    $categories = Category::all();

    return view('auth.register')->with('categories',$categories);
}


Solution 1:[1]

Change your create controller function something like this

protected function create(Request $request)
{
    $category = $request->categories;
    // You can access the categories as $category[index]

    // modifica dati da creare. Aggiunti p_iva, address, business_name
    return User::create([
        'business_name' => $request['business_name'],
        'address' => $this->getAddress($request['street'], $request['civic'], $request['city'], $request['state'], $request['cap']),
        'p_iva' => $request['p_iva'],
        'email' => $request['email'],
        'password' => Hash::make($request['password']),
    ]);
}

Then you would receive all form data in the $request variable. dd the $category variable to see what you are getting and then perform the desired operation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1