Laravel Corcel WooCommerce - Add product categories

710 Views Asked by At

I am using the laravel package "corcel/woocommerce" and I am trying to attach product categories to the created product.

        $product = Product::create([
                'post_title' => 'Product name',
                'post_content' => 'Post description',
                'post_status' => 'publish',
                'post_type' => 'product'
                ]
        );
        $product->createMeta([
            '_sku' => '1234',
            '_regular_price' => '10.00',
            '_sale_price' => '5.00',
            '_thumbnail_id' => 10
            // other wp_postmeta product meta values...
        ]);

Here is where I am trying to add a category:

$product->categories()->create([
'cat_name' => 'Test'
]);

But I get the following error:

   Illuminate\Database\Eloquent\MassAssignmentException 

  Add [cat_name] to fillable property to allow mass assignment on [Corcel\WooCommerce\Model\ProductCategory][.][1]

Does anyone have any ideas about how I can attach a WooCommerce category to the product please?

1

There are 1 best solutions below

3
OMR On

in your model ProductCategory you should define the $fillable attribute to support mass assignment:

class ProductCategory extends Model
{
 protected $fillable = ['cat_name']; // not only cat_name but also all fillable attributes
}

if you can't change the ProductCategory model, the change the way you save it:

$productCategory= new ProductCategory();
$productCategory->cat_name='test'; // if the is another required attributes, fill them.
$productCategory->save();
$product->categories()->attach($productCategory->id);