55namespace App \Livewire ;
66
77use App \Models \Product ;
8+ use App \Models \ProductVariant ;
89use Darryldecode \Cart \Facades \CartFacade ;
910use Filament \Notifications \Notification ;
1011use Illuminate \Contracts \View \View ;
@@ -14,21 +15,35 @@ final class VariantsSelector extends Component
1415{
1516 public Product $ product ;
1617
17- public ?Product $ selectedVariant = null ;
18+ public ?ProductVariant $ selectedVariant = null ;
19+
20+ public function mount (): void
21+ {
22+ $ this ->selectedVariant ?->loadMissing([
23+ 'prices ' => function ($ query ) {
24+ $ query ->whereRelation ('currency ' , 'code ' , current_currency ());
25+ },
26+ 'prices.currency ' ,
27+ ]);
28+
29+ }
1830
1931 public function addToCart (): void
2032 {
33+ $ model = $ this ->selectedVariant ?? $ this ->product ;
34+
2135 // @phpstan-ignore-next-line
2236 CartFacade::session (session ()->getId ())->add ([
23- 'id ' => $ this ->selectedVariant ? $ this ->selectedVariant ->id : $ this ->product ->id ,
24- 'name ' => $ this ->selectedVariant
25- ? $ this ->product ->name . ' / ' . $ this ->selectedVariant ->name
26- : $ this ->product ->name ,
27- 'price ' => $ this ->selectedVariant && $ this ->selectedVariant ->price_amount
28- ? $ this ->selectedVariant ->price_amount
29- : $ this ->product ->price_amount ,
37+ 'id ' => $ model ->id ,
38+ 'name ' => $ this ->product ->name ,
39+ 'price ' => $ model ->getPrice ()->amount ->amount ,
3040 'quantity ' => 1 ,
31- 'associatedModel ' => $ this ->selectedVariant ?->load('parent ' ) ?? $ this ->product ,
41+ 'attributes ' => $ this ->selectedVariant
42+ ? $ this ->selectedVariant ->values ->mapWithKeys (function ($ value ) {
43+ return [$ value ->attribute ->name => $ value ->value ];
44+ })->toArray ()
45+ : [],
46+ 'associatedModel ' => $ model ,
3247 ]);
3348
3449 $ this ->dispatch ('cartUpdated ' );
0 commit comments