Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kgp43's avatar
Level 2

Add unique company to table and make user-relation in pivot table

Hi,

I'm not sure how to solve this problem:

I got 3 tables:

  • users
  • companies
  • company_user

A user can add a new company to the database. Each company got a CVRnumber (reg.number) that has to be unique. A relation is added to the pivot table.

The problem is when adding a company to the table that already exists. I receive this error: "the cvr has already been taken". What I would like, is to skip adding the company, since it already exists, and just add the relation to the pivot table.

How do you guys suggest I handle that part?

Some of my code listed below:

Store method in my controller:

$company->owner_id = $user->id;
            $company->reg = $cvr;
            $company->name = $api['name'];
            $company->address = $api['address'];
            $company->zipcode = $api['zipcode'];
            $company->city = $api['city'];
            $company->country = 'dk';
            $company->phone = $api['phone'];
            
            $company->save();
            
            # Add to pivot table
            $company->users()->attach($user);
            
            # Status message
            Toastr::success($company->name.' blev tilføjet din konto', 'Succes');
            
            return redirect()->route('company.index');

FormRequest:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Brian2694\Toastr\Facades\Toastr;

use Auth;

class CreateCompany extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        
        return [
            'cvr'     => 'required|numeric|digits:8|unique:companies,reg',
        ];
        
    }
    
    # Error messages
    protected function formatErrors(Validator $validator)
    {
        
        $messages = $validator->messages();

        foreach ($messages->all() as $message)
        {
            Toastr::error($message, 'Failed', ['timeOut' => 10000]);
        }

        return $validator->errors()->all();
    }
    
}

, Kenneth

0 likes
1 reply
kgp43's avatar
Level 2

I get the error because of the rules i made, which is correct.

But that's not really the functionality I want - not sure what to change.

It should just skip adding the company, if cvrnumber already exist - instead of aborting.

public function rules()
    {
        
        return [
            'cvr'     => 'required|numeric|digits:8|unique:companies,reg',
        ];
        
    }

Please or to participate in this conversation.