SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value
Hello everyone I ran into a problem during the implementation of Multi-tenancy, I tried to do everything according to the documentation, but apparently I made a mistake somewhere. RegisterCompany.php :
Company model :
User model :
<?php
// use ...
class RegisterCompany extends RegisterTenant
{
public static function getLabel(): string
{
return 'Create company';
}
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function form(Form $form): Form
{
return $form
->schema([
Select::make('type')
->options([
'General' => 'General',
'Simplified' => 'Simplified',
'Patent' => 'Patent'
]),
TextInput::make('name'),
TextInput::make('short_name'),
]);
}
protected function handleRegistration(array $data): Company
{
$company = Company::create($data);
$company->members()->attach(auth()->user());
return $company;
}
}<?php
// use ...
class RegisterCompany extends RegisterTenant
{
public static function getLabel(): string
{
return 'Create company';
}
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function form(Form $form): Form
{
return $form
->schema([
Select::make('type')
->options([
'General' => 'General',
'Simplified' => 'Simplified',
'Patent' => 'Patent'
]),
TextInput::make('name'),
TextInput::make('short_name'),
]);
}
protected function handleRegistration(array $data): Company
{
$company = Company::create($data);
$company->members()->attach(auth()->user());
return $company;
}
}Company model :
public function members():BelongsToMany
{
return $this->belongsToMany(User::class);
}
public function Requisite() : HasOne
{
return $this->hasOne(CompanyRequisite::class);
} public function members():BelongsToMany
{
return $this->belongsToMany(User::class);
}
public function Requisite() : HasOne
{
return $this->hasOne(CompanyRequisite::class);
}User model :
public function getTenants(Panel $panel): array|\Illuminate\Support\Collection
{
return $this->Companies;
}
public function Companies(): BelongsToMany
{
return $this->belongsToMany(Company::class);
}
public function canAccessTenant(Model $tenant): bool
{
return $this->companies->contains($tenant);
}public function getTenants(Panel $panel): array|\Illuminate\Support\Collection
{
return $this->Companies;
}
public function Companies(): BelongsToMany
{
return $this->belongsToMany(Company::class);
}
public function canAccessTenant(Model $tenant): bool
{
return $this->companies->contains($tenant);
}Solution
yes
so you have to add
INSERT INTO
`companies` (
`name`,
`short_name`,
`type`,
`updated_at`,
`created_at`
)INSERT INTO
`companies` (
`name`,
`short_name`,
`type`,
`updated_at`,
`created_at`
)so you have to add
user_iduser_id to the $data$data and make sure its fillablefillable in the model company$data['user_id'] = auth()->user()->id
$company = Company::create($data);$data['user_id'] = auth()->user()->id
$company = Company::create($data);