Problem using Many to Many relationship, using filament v2.

SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value
INSERT INTO
  `books` (
    `image`,
    `title`,
    `author_id`,
    `publication_date`,
    `copies`,
    `updated_at`,
    `created_at`
  )
VALUES
  (
    AxfnWejAwc4eq4h3tIXO88baytGB8F - metaYm9va19ub3VuXzAwMV8wMTY3OS5qcGc = -.jpg,
    test,
    1,
    AS,
    AS,
    2023 -12 -13 17: 40: 37,
    2023 -12 -13 17: 40: 37
  )

this is my form

 public static function form(Form $form): Form
    {
    return $form
        ->schema([
            Card::make()
            ->schema([
                FileUpload::make('image')->image(),
                TextInput::make('title')
                ->required()
                ->maxLength(255),
                Select::make('author_id')   
                ->relationship('author', 'full_name')
                ->required(),
                Select::make('category_id')
                ->multiple()    
                ->relationship('categories', 'name')
                ->preload()
                ->required(),
                TextInput::make('publication_date')
                ->required()
                ->maxLength(255),
                TextInput::make('copies')
                ->required()
                ->maxLength(255)
            ])
        ]);
    }


my models

    class Book extends Model
    {
        use HasFactory;

        protected $casts = [
            'category_id' => 'array',
        ];

        protected $fillable = ['author_id','image','title','language','publication_date','copies']; 

        public function author(){
            return $this->belongsTo(Author::class);
        } 

        public function categories(){
            return $this->belongsToMany(Category::class);
        }  
    }


class Category extends Model
{
    use HasFactory;

    protected $fillable = ['name']; 
        
    public function books(){
        return $this->belongsTo(Book::class);
    }  
}


example input
UWSCDb.png
Was this page helpful?