تماشای این درس نیاز به اشتراک حرفه‌ای دارد.

Refactoring With match()0:00

So, now that we verified that this is working, we can optimize the code a little bit. So, instead of using two if statements, we can use the match function that is provided by php. So, whatever matches the guess value will be true or false. And in case it's true, we want to create the session based on the sessionId. If it's false, this means the User is logged in. We want to use the card that is assigned to the User or create a new card if necessary. And the card itself will be returned to the card variable that we defined here at the top. And now we can remove the code below, and this should still work.

Adding Card Items Relation0:41

top. And now we can remove the code below, and this should still work. So, if we add something to the card, you can see that it is still working. Next, we can continue adding the variant to our card. So, if we look at our table of our card items, we have the quantity, we have our product_variant_id, and the quantity. So, let's switch to our Card model and let's implement that relation first. So, let's create a new function called items, and let's make sure that it returns a hasMany relationship, and that hasMany relationship is, of course, associated to our CardItem model.

Creating CardItem Records1:16

hasMany relationship is, of course, associated to our CardItem model. So, we can go back to our action, and now we want to add the variant to our card. So, we can say cardItems and call the create method. So, now we can set our productVariantID and set the quantity to 1. So, let's summarize, based on whether the User is logged in or not, we'll create a card depending on the sessionID or the userID, and finally, we'll add the cardItem to our card based on our productVariantID, and we'll set the quantity to 1.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟