Adding products to bulk basket

Help for integrating the Laravel package
Forum rules
Always add your Laravel, Aimeos and PHP version as well as your environment (Linux/Mac/Win)
Spam and unrelated posts will be removed immediately!
hyalcin
Posts: 11
Joined: 09 Aug 2024, 13:22

Adding products to bulk basket

Post by hyalcin » 23 Aug 2024, 11:43

I want to add the selected products to the basket in bulk and continue to the checkout page. I would be happy if you could give me information on how to do this.
I am currently storing selected products in Products in Local Storage. Also, I am getting the error Success: {success: false, message: '{success: false, message: 'No article was found for the product with ID "39" and the selected attributes'}' from the controller I created.
"php": "^8.1", "aimeos/aimeos-laravel": "~2024.07", laravel : 10

Code: Select all

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Aimeos\MShop;
use Aimeos\Controller\Frontend;
use Illuminate\Support\Facades\Log;

class CustomBasketController extends Controller
{
    public function addCustomProduct(Request $request)
    {
        $products = $request->all();

        if (empty($products)) {
            return response()->json(['success' => false, 'message' => 'No products found'], 400);
        }

        try {
            // Aimeos bağlamını oluştur
            $context = app('aimeos.context')->get();
            $locale = app('aimeos.locale')->getBackend($context, 'default');
            $context->setLocale($locale);

            // Sepet kontrolcüsü ve ürün yöneticisini oluştur
            $basketController = Frontend::create($context, 'basket');
            $productManager = MShop::create($context, 'product');

            // Sepeti al
            $basket = $basketController->get();

            // Ürünleri işlemek için döngü
            foreach ($products as $product) {
                $productId = $product['dataid'] ?? null;
                $quantity = $product['count'] ?? 1;
                $attributes = $product['attributes'] ?? [];

                if ($productId) {
                    // Ürünü ID ile arıyoruz
                    $filter = $productManager->filter(true);
                    $filter->add('product.id', '==', $productId);
                    $productsFound = $productManager->search($filter);

                    if ($productsFound->count() > 0) {
                        $productItem = $productsFound->first();

                        // Ürünü sepete ekle
                        $basketController->addProduct(
                            $productItem,
                            (float) $quantity,
                            $attributes
                        );
                    } else {
                        return response()->json(['success' => false, 'message' => 'Product with ID ' . $productId . ' not found']);
                    }
                } else {
                    return response()->json(['success' => false, 'message' => 'Product ID is missing']);
                }
            }

            // Sepeti kaydet
            $basketController->save();

            return response()->json(['success' => true, 'message' => 'Basket updated successfully!']);
        } catch (\Exception $e) {
            // Hata yönetimi
            Log::error('Error adding products to basket: ' . $e->getMessage());
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}

User avatar
aimeos
Administrator
Posts: 8262
Joined: 01 Jan 1970, 00:00

Re: Adding products to bulk basket

Post by aimeos » 24 Aug 2024, 15:16

Use the addProduct() method of the basket controller to add one product to the basket:
https://github.com/aimeos/ai-controller ... hp#L78-L92

Use a loop over the required product parameters to add several products in our own controller.
Professional support and custom implementation are available at Aimeos.com
If you like Aimeos, Image give us a star

hyalcin
Posts: 11
Joined: 09 Aug 2024, 13:22

Re: Adding products to bulk basket

Post by hyalcin » 26 Aug 2024, 07:50

Code: Select all

 document.getElementById('productForm').addEventListener('submit', function(event) {
        event.preventDefault();  // Prevent form submission
        let csrfToken = document.querySelector('input[name="_token"]').value;
    
         // Sadece varyantı olan ürün için kontrol yapıyoruz
        let allVariantsSelected = true;
        selectedProducts.forEach(product => {
            if (product.dataid === '39' && (!product.attributes || Object.keys(product.attributes).length === 0)) {
                allVariantsSelected = false;
            }
        });

        if (!allVariantsSelected) {
            alert('Please select all necessary variants for the product with variants before adding to the basket.');
            return;
        }
    
        fetch("/custom-basket/add", {
            method: "post",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken
            },
            body: JSON.stringify(selectedProducts)
        })
        .then((response) => response.json())
        .then(data => {
            if (!data) {
                console.log('Empty response from server.');
            } 
            else {
                console.log('Success:', data); 
                if (data.success) {
                    checkAuthenticationAndRedirect(); 
                } else {
                    alert(data.message); 
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });
console.log('Success:', data); I get an error message from this line.
Success: {success: false, message: 'An error occurred: Das Produkt mit der ID "1" darf nicht direkt zum Warenkorb hinzugefügt werden'} "The product with ID "1" may not be added directly to the shopping cart."

Code: Select all

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Aimeos\MShop;
use Aimeos\Controller\Frontend;
use Illuminate\Support\Facades\Log;

class CustomBasketController extends Controller
{
    public function addCustomProduct(Request $request)
    {
        $products = $request->all();

        if (empty($products)) {
            return response()->json(['success' => false, 'message' => 'No products found'], 400);
        }

        try {
            // Aimeos bağlamını oluştur
            $context = app('aimeos.context')->get();
            $locale = app('aimeos.locale')->getBackend($context, 'default');
            $context->setLocale($locale);

            // Sepet kontrolcüsü ve ürün yöneticisini oluştur
            $basketController = Frontend::create($context, 'basket');
            $productManager = MShop::create($context, 'product');

            // Sepeti al
            $basket = $basketController->get();

            // Ürünleri işlemek için döngü
            foreach ($products as $product) {
                $productId = $product['dataid'] ?? null;
                $quantity = (float)($product['count'] ?? 1);
                $variant = $product['attributes'] ?? [];
                $config = [];
                $custom = [];
                $stocktype = 'default';
                $siteId = null;

                if ($productId) {
                    // Ürünü ID ile arıyoruz
                    $filter = $productManager->filter(true);
                    $filter->add('product.id', '==', $productId);
                    $productsFound = $productManager->search($filter);

                    if ($productsFound->count() > 0) {
                        $productItem = $productsFound->first();

                        // Ürün türünü kontrol ediyoruz
                        $productType = $productItem->getType();

                        if ($productType === 'selection' && empty($variant)) {
                            return response()->json(['success' => false, 'message' => 'Please select a variant before adding the product to the basket.']);
                        }

                        if ($productType === 'bundle' && empty($variant)) {
                            return response()->json(['success' => false, 'message' => 'Please select all necessary options before adding the product to the basket.']);
                        }

                        // Ürünü sepete ekliyoruz
                        $basketController->addProduct(
                            $productItem,
                            $quantity,
                            $variant,
                            $config,
                            $custom,
                            $stocktype,
                            $siteId
                        );
                    } else {
                        return response()->json(['success' => false, 'message' => 'Product with ID ' . $productId . ' not found']);
                    }
                } else {
                    return response()->json(['success' => false, 'message' => 'Product ID is missing']);
                }
            }

            // Sepeti kaydet
            $basketController->save();

            return response()->json(['success' => true, 'message' => 'Basket updated successfully!']);
        } catch (\Exception $e) {
            // Hata yönetimi
            Log::error('Error adding products to basket: ' . $e->getMessage());
            return response()->json(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()], 500);
        }
    }
}
Why can't I add my products to the basket? I would be happy if you could help me with this.

User avatar
aimeos
Administrator
Posts: 8262
Joined: 01 Jan 1970, 00:00

Re: Adding products to bulk basket

Post by aimeos » 27 Aug 2024, 19:57

Most likely, your product has to category assigned:
https://github.com/aimeos/ai-controller ... ry.php#L54
Professional support and custom implementation are available at Aimeos.com
If you like Aimeos, Image give us a star

Post Reply