Add product to basekt via custom php command

How to configure and adapt Aimeos based shops as developer
Forum rules
Always add your Aimeos and PHP version as well as your environment (Linux/Mac/Win)
Spam and unrelated posts will be removed immediately!
User avatar
BeatGurtner
Posts: 1
Joined: 16 Jan 2025, 09:47

Add product to basekt via custom php command

Post by BeatGurtner » 16 Jan 2025, 09:50

i try to add a product to my basket with this code:

I see a success message in postman, but its not added to my basket: http://127.0.0.1:8000/shop/basket

I work with PHP 8.3.14 and aimeos 2024.10 on a mac.

Code: Select all

{"status":"success","message":"Product added to cart","basket_info":{"product_count":1,"total_price":"5,544.00","currency":"USD","product_code":"123456","session_id":"T3Fq6X9g8o6D7XOR9rVwlxCmfjVc09qU2XzpHBNi","product_id":"18"}}

Code: Select all

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Aimeos\Controller\Frontend;
use Aimeos\MShop\Exception as MShopException;
use Illuminate\Support\Facades\View;

class CustomCartController extends Controller
{
    public function addToCart(Request $request)
    {
        try {
            // Get the context with locale
            $context = app('aimeos.context')->get(false);
            
            // Set up the locale with currency and language
            $locale = app('aimeos.locale')->get($context, [
                'lang' => 'en',
                'currency' => 'USD'
            ]);
            $context->setLocale($locale);
            
            // Validate input
            $productCode = $request->input('product_id');
            $quantity = max(1, (int)$request->input('quantity', 1));
            
            if (!$productCode) {
                return response()->json([
                    'status' => 'error', 
                    'message' => 'Product code is required'
                ], 400);
            }

            // Get product manager
            $productManager = \Aimeos\MShop::create($context, 'product');
            
            // Create base filter
            $filter = $productManager->filter(true);
            $filter->add('product.code', '==', $productCode);
            $filter->add('product.status', '==', 1);
            
            // Find the product with all required domains
            $product = $productManager->search(
                $filter, 
                ['text', 'price', 'media', 'attribute', 'product', 'catalog', 'stock']
            )->first();
            
            if (!$product) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Product not found or not active: ' . $productCode
                ], 404);
            }

            // Verify product is in a category
            $listManager = \Aimeos\MShop::create($context, 'product/lists');
            $filter = $listManager->filter(true);
            $filter->add([
                $filter->and([
                    $filter->is('product.lists.domain', '==', 'catalog'),
                    $filter->is('product.lists.parentid', '==', $product->getId()),
                    $filter->is('product.lists.status', '==', 1),
                ])
            ]);
            
            $listItems = $listManager->search($filter);
            
            if ($listItems->isEmpty()) {
                // If no category relationship found, try rebuilding the index
                exec('php artisan aimeos:jobs index/rebuild');
                
                return response()->json([
                    'status' => 'error',
                    'message' => 'Product is not associated with any category. Please assign it to a category first.',
                    'debug_info' => [
                        'product_id' => $product->getId(),
                        'product_code' => $product->getCode(),
                    ]
                ], 400);
            }

            // Get the basket controller
            $basketController = \Aimeos\Controller\Frontend::create($context, 'basket')
                ->setType('default');
            
            // Add product to basket
            $basketController->addProduct(
                $product,
                $quantity,
                [],             // Variant attributes
                [],             // Config attributes
                [],             // Custom attributes
                'default',      // Stock type
                null            // Site ID
            );
            
            // Get basket contents for verification
            $basket = $basketController->get();
            $products = $basket->getProducts();
            
            return response()->json([
                'status' => 'success',
                'message' => 'Product added to cart',
                'basket_info' => [
                    'product_count' => count($products),
                    'total_price' => number_format($basket->getPrice()->getValue(), 2),
                    'currency' => $basket->getPrice()->getCurrencyId(),
                    'product_code' => $productCode,
                    'session_id' => session()->getId(),
                    'product_id' => $product->getId(),
                ]
            ]);

        } catch (MShopException $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'trace' => $e->getTraceAsString()
            ], 400);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 500);
        }
    }
}

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

Re: Add product to basekt via custom php command

Post by aimeos » 16 Jan 2025, 10:03

There are a few problems in your code.

Code: Select all

            $productCode = $request->input('product_id');
Use the product ID if possible because it's easier to handle.

Code: Select all

            $filter = $productManager->filter(true);
            $filter->add('product.code', '==', $productCode);
            $filter->add('product.status', '==', 1);
filter(true) automatically adds a condition for product.status > 0

Code: Select all

            $listManager = \Aimeos\MShop::create($context, 'product/lists');
            $filter = $listManager->filter(true);
            $filter->add([
                $filter->and([
                    $filter->is('product.lists.domain', '==', 'catalog'),
                    $filter->is('product.lists.parentid', '==', $product->getId()),
                    $filter->is('product.lists.status', '==', 1),
                ])
            ]);
Don't use list managers directly. Instead. Use the product:has() search function of the product manager:

Code: Select all

$filter->add($filter->make('product:has', ['catalog']);
But you don't need that at all because it's already checked when you add the product to the basket.

Code: Select all

                // If no category relationship found, try rebuilding the index
                exec('php artisan aimeos:jobs index/rebuild');
Never execute cronjobs in HTTP requests as they are long lasting operations which will exceed the PHP runtime limit!

Code: Select all

            $basketController->addProduct(
                $product,
                $quantity,
                [],             // Variant attributes
                [],             // Config attributes
                [],             // Custom attributes
                'default',      // Stock type
                null            // Site ID
            );
You can skip all arguments after "$quantity" because these are also the default values.

Also, make sure that you send the Laravel session cookie along with each request. Otherwise, you always get back a new and empty basket.
Professional support and custom implementation are available at Aimeos.com
If you like Aimeos, Image give us a star

Post Reply