Bagisto Forum

    Bagisto

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups

    Create product with image programmatically

    General Discussion
    product image
    2
    5
    224
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • S
      saaraan last edited by

      Can anyone show me how to properly create a product and attach the local image or the image url? right now product is created succesfully in my bagisto package, but image is not being attached to the product and not processed at all. am I doing something wrong? thanks in advance

      try {
              // Example: Use the default attribute family
              $attributeFamily = $this->attributeFamilyRepository->findOneByField('code', 'default');
              $channel = Channel::where('code', 'default')->first();
              $locale = Locale::where('code', 'en')->first();
      
              // Fetch the image
              $imageUrl = 'https://example.com/download_image.jpg';
              $response = Http::get($imageUrl);
      
              // Check if the HTTP request was successful
              if (!$response->successful()) {
                  throw new \Exception('Failed to fetch image from URL: ' . $imageUrl);
              }
      
              $imageContents = $response->body();
              $filename = 'product_' . uniqid() . '.jpg';
              $tempImagePath = storage_path('app/temp/' . $filename);
              Storage::disk('local')->put('temp/' . $filename, $imageContents);
      
              // Verify the file was saved successfully
              if (!file_exists($tempImagePath)) {
                  throw new \Exception('Failed to save temporary image to: ' . $tempImagePath);
              }
      
              // Create an UploadedFile instance
              $uploadedFile = new UploadedFile(
                  $tempImagePath,
                  $filename,
                  mime_content_type($tempImagePath) ?: 'image/jpeg',
                  null,
                  true
              );
      
              $data = [
                  'type'                  => 'simple',
                  'attribute_family_id'   => $attributeFamily->id,
                  'sku'                   => 'simple-product-' . uniqid(),
                  'url_key'               => 'simple-product-url-' . uniqid(),
                  'name'                  => 'product1',
                  'price'                 => 99.99,
                  'weight'                => 1.0,
                  'short_description'     => 'description',
                  'description'           => 'long description',
                  'status'                => 1,
                  'visible_individually'  => 1,
                  'channels'              => [$channel->id],
                  'categories'            => [4],
                  'inventories'           => [1 => 100],
                  'images'                => [0 => $uploadedFile],
                  'locale'                => $locale->code,
              ];
      
              // Create the product
              $product = $this->productRepository->create($data);
              if (!$product) {
                  throw new \Exception('Product creation failed.');
              }
      
              // Update the product
              $updatedProduct = $this->productRepository->update($data, $product->id);
              if (!$updatedProduct) {
                  throw new \Exception('Product update failed.');
              }
      
              // Refresh the flat indexer
              $this->flatIndexer->refresh($updatedProduct);
              
              return response()->json([
                  'message' => 'Product created successfully!',
                  'product' => $updatedProduct,
              ]);
      
          } catch (\Exception $e) {
              \Log::error('Error creating product: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);
              return response()->json(['message' => 'Error creating product.', 'error' => $e->getMessage()], 500);
          }
      
      1 Reply Last reply Reply Quote 0
      • R
        rishabh-webkul19 last edited by

        Hello @saaraan

        Kindly let us know the bagisto version you are using.

        Regards

        S 1 Reply Last reply Reply Quote 0
        • S
          saaraan @rishabh-webkul19 last edited by

          @rishabh-webkul19 hello sir, the bagisto version is v2.3.7, which is latest. I could not find the proper way to create a product on bagisto documentation. I am just shooting in the dark with code above, my goal is simple :

          1. Create product with variation : colors & size
          2. attach the image (local or remote)

          i did find a snippet in services folder (package directory) that does create the product but not sure how variants and images are processed. thank you.

          public function createProduct(array $productData, array $variants = []): \Webkul\Product\Models\Product
              {
                  return DB::transaction(function () use ($productData, $variants) {
                      // 1. Create parent product
                      $product = $this->productRepository->create($productData);
          
                      // 2. If variants are provided, attach them
                      foreach ($variants as $attributeCode => $values) {
                          foreach ($values as $value) {
                              $childData = array_merge($productData, [
                                  'parent_id'      => $product->id,
                                  'type'           => 'simple',
                                  'sku'            => $productData['sku'] . '-' . strtolower($value),
                                  $attributeCode   => $value, // e.g. 'color' => 'Red'
                              ]);
          
                              $child = $this->productRepository->create($childData);
          
                              // inventory (optional)
                              $this->productInventoryRepository->create([
                                  'product_id'   => $child->id,
                                  'inventory_source_id' => 1, // default inventory source
                                  'qty'          => 10,
                              ]);
                          }
                      }
          
                      return $product->load('variants');
                  });
              }
          }
          
          1 Reply Last reply Reply Quote 0
          • R
            rishabh-webkul19 last edited by

            Hello @saaraan

            Variants should be stored like this. Check the below code for reference,

            foreach ($values as $value) { $childData = array_merge($productData, [ 'parent_id' => $product->id, 'type' => 'simple', 'sku' => $productData['sku'] . '-' . strtolower($value), $attributeCode => $value, // e.g. 'color' => 'Red' ]); $child = $this->productRepository->create($childData); // inventory (optional) $this->productInventoryRepository->create([ 'product_id' => $child->id, 'inventory_source_id' => 1, // default inventory source 'qty' => 10, ]); }

            S 1 Reply Last reply Reply Quote 0
            • S
              saaraan @rishabh-webkul19 last edited by

              @rishabh-webkul19 Thank you for your reply, what's proper way to attach the image? how does bagisto process the product image? thank you.

              $ImagePath = '/storage/app/temp/image.jpg'; 
              $uploadedFile = new UploadedFile(
                $ImagePath,
                'imageFileName',
                'image/jpeg',
                null,
                true
              );
              
              1 Reply Last reply Reply Quote 0
              • First post
                Last post