F
Filament11mo ago
tg

Must <foreign_model>_id be fillable to save it on resource creation?

I have two models, Opportunity -> belongsTo -> Company. The opportunities table has a company_id field which is * not nullable* to ensure data integrity. The Opportunity model has a relationship company.
class Opportunity extends Model
{
protected $fillable = [
// attributes of Opportunity, WITHOUT `company_id`
];

public function company(): BelongsTo
{
return $this->belongsTo(Company::class, 'company_id');
}
}
class Opportunity extends Model
{
protected $fillable = [
// attributes of Opportunity, WITHOUT `company_id`
];

public function company(): BelongsTo
{
return $this->belongsTo(Company::class, 'company_id');
}
}
Note that company_id is not included in $fillable, as other sections of my app outside the Filament admin panel should not be able to alter this relationship through requests. My OpportunityResource::form field for the relationship:
Forms\Components\Select::make('company_id')
->label('Company')
->relationship(name: 'company', titleAttribute: 'name')
->required(),
Forms\Components\Select::make('company_id')
->label('Company')
->relationship(name: 'company', titleAttribute: 'name')
->required(),
On the EditOpportunity page, I can alter the associated company just fine. On CreateOpportunity however, I can select a company but I get this error:
SQLSTATE[HY000]: General error: 1364 Field 'company_id' doesn't have a default value
SQLSTATE[HY000]: General error: 1364 Field 'company_id' doesn't have a default value
If I add company_id to Opportunity::$fillable, it works as expected. I'd expect consistent behavior between Create and Edit, so either require company_id in $fillable on both operations or on neither.
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server