jeudi 23 septembre 2021

assign multiple category in laravel

this is code use for importing products through csv file to laravel

private function getCategoryIdsFromNames($categories, $subCategory)
{
    $categoryArray = $this->explode($categories);
    if (!$categoryArray)
        return false;
    $categoryIds = [];
    foreach ($categoryArray as $categoryName) {
        $category = CategoryTranslation::query()->where('name', $categoryName)->where('locale', 'en')->first();
        if ($category) {
            $categoryIds[] = $category->category_id;
        } else {
            $newCategory = [
                'name' => $categoryName,
                'is_active' => "1",
                'parent_id' => null,
                'is_searchable' => "1",
            ];
            $category = Category::query()->create($newCategory);
            $categoryIds[] = $category->id;
        }
    }
    return $categoryIds;
}

private function getFinalCategoryIds($categories)
{
    $names = explode('>', $categories);
    $parentCategoryId = null;
    $categoryId = null;
    foreach ($names as $name) {
        $categoryIds = CategoryTranslation::query()->where('name', $name)->where('locale', 'en')->get()->pluck("category_id");
        $categoryId = null;
        if (!empty($categoryIds)) {
            $category = Category::query()->whereIn("id", $categoryIds)->where('parent_id', $parentCategoryId)->first();
            if ($category)
                $categoryId = $parentCategoryId = $category->id;
        }
        if (is_null($categoryId)) {
            $newCategory = [
                'name' => $name,
                'is_active' => "1",
                'parent_id' => $parentCategoryId,
                'is_searchable' => "1",
            ];
            $category = Category::query()->create($newCategory);
            $categoryId = $parentCategoryId = $category->id;
        }
    }
    return [$categoryId];
}

Currently its importing/assigning one category to one product. i want to multiple category import/assign to single product in laravel. divide multiple category by ",". Please any help appreciated .



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire