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