F
Filament13mo ago
Tritus

Relationship "id", fillable and saveRelationships

Hi everyone, There is probably something I misuderstand. I have a "Course" entity and a "CourseCategory" entity. My relationship is as simple as :
public function course_category(): BelongsTo
{
return $this->belongsTo(CourseCategory::class);
}
public function course_category(): BelongsTo
{
return $this->belongsTo(CourseCategory::class);
}
In my CourseResource I have the following select :
Forms\Components\Select::make('course_category_id')
->relationship('course_category', 'title')
->searchable()
->required(),
Forms\Components\Select::make('course_category_id')
->relationship('course_category', 'title')
->searchable()
->required(),
And in my CreateCourse :
protected function handleRecordCreation(array $data): Model
{
return auth()->user()->courses()->create($data);
}
protected function handleRecordCreation(array $data): Model
{
return auth()->user()->courses()->create($data);
}
But if I submit my form, I always get "Field 'course_category_id' doesn't have a default value". The issue disappears if I add "course_category_id" in the $fillable of Course, but I do not like that idea.
I'm seeing there is the "saveRelationships(); " who is called automatically, but I'm not sure to see how it works because if I add course_category_id in the $fillable, it is totally useless, and if not, I have the issue shown above. Can someone help me understand what's the best way to deal with that ? Thanks !
7 Replies
toeknee
toeknee13mo ago
Is this on a form in a custom livewire component?
Tritus
Tritus13mo ago
No, I have used the php artisan make:filament-resource Course --generate So I'm using the "form" method of CourseResource.php, and the handleRecordCreation() method of the CreateCourse.php
toeknee
toeknee13mo ago
You probably haven't added course_category_id to your models fillable and the database isn't nullable so no value is being set
Tritus
Tritus13mo ago
Yes I do not want to add it in my fillable. I finally end up with adding ->nullable() on the foreignId(), and now there is no issues. Thanks. I thought I misunderstood something, but finally not, it's just that I had to do one of these modifications (adding in fillable or nullable())
toeknee
toeknee13mo ago
So you want it to be nullable? as if it's not fillable you will not be able to assign the value which makes it pointless having a course_category_id and you should dehydrate it if you don't want it.
Tritus
Tritus13mo ago
From what I'm seeing, the course_category_id is filled automatically thanks to the saveRelationships() method. -> The Course is created with no course_category_id -> Then saveRelationships() fills the course_category_id automatically And it fits my needs. Is it not a good way to deal with that issue? I'm new to Laravel Filament
toeknee
toeknee13mo ago
That sounds about right, just strange that the course_category_id is being saved to when it's not fillable. If it works then great.