Many to many relationship in filament
i have this code for create new product with units
class CreateProduct extends CreateRecord
{protected static string $resource = ProductResource::class;
protected function handleRecordCreation(array $data): Product
{
Log::info('FormData:', $data);
return DB::transaction(function () use ($data) {
$product = Product::create($data);
if (isset($data['units']){foreach ($data['units'] as $unitData)
{
Log::info('Unit Data:', $unitData);
if (!isset($unitData['price']) || is_null($unitData['price']))
{
Log::error('Price is missing for unit', $unitData);continue;} $price = intval($unitData['price']);
$product->units()->attach($unitData['unit_id'], ['price' => $price]);
Log::info('Attached Unit with Price:', [
'product_id' => $product->id,
'unit_id' => $unitData['unit_id'],
'price' => $price, ]);
} } return $product;}); }} when i create 2 uints with prices or above i saw error in third image how can i solve it product mode has class Product extends Model {use HasFactory; protected $table = "products" ; protected $fillable = [ 'name_ar' ,'name_en' , 'description_ar' , 'description_en' , 'image' ,'category_id' , 'is_activated', ]; public function toArray() { $array = parent::toArray(); $array['units'] = $this->units->map(function ($unit) {return ['id' => $unit->id, 'name' => $unit->name, 'price' => $unit->price,]; }); return $array; } public function units() { return $this->belongsToMany(Unit::class, 'products_units')->withPivot('price');} }
} } return $product;}); }} when i create 2 uints with prices or above i saw error in third image how can i solve it product mode has class Product extends Model {use HasFactory; protected $table = "products" ; protected $fillable = [ 'name_ar' ,'name_en' , 'description_ar' , 'description_en' , 'image' ,'category_id' , 'is_activated', ]; public function toArray() { $array = parent::toArray(); $array['units'] = $this->units->map(function ($unit) {return ['id' => $unit->id, 'name' => $unit->name, 'price' => $unit->price,]; }); return $array; } public function units() { return $this->belongsToMany(Unit::class, 'products_units')->withPivot('price');} }





1 Reply
please read the #✅┊rules on code formatting.
many to many with a pivot means the pivot doesn't house data other than the id's of the products usually