Wakanda's avatar
Level 10

Best way to implement product attributes

Hi Devs.

Am working on an e-commerce platform. I have a Product model soon to have product attributes.

Attributes List


Color
Size
Weight //can be Kgs or Pcs
Shape

So should I have Models & Tables for each attribute? Or have a single attribute model & table.

Which one is the best way in terms of scalability and how should I go about it?

A product will have multiple attributes or only one eg color only.

@MichalOravec @Snapey

0 likes
3 replies
Tray2's avatar
Tray2
Best Answer
Level 73

Depending a bit on how you have set up the other tables but I would most likely create a product_attributes table.

It would look something like this

  • id
  • product_id (references id in the product table)
  • attribute_name
  • attribute_value

So a product with a single attribute would look like this

1, 1, color, yellow

One with multiple attributes would look like this

1, 1, color, blue
2, 1, height, 20cm
3, 1, diameter, 5"
LaraBishal's avatar

I would make two tables tbl_attributes with something like this

	    $table->bigIncrements('id');
           $table->string('code')->unique();
           $table->string('name');
           $table->enum('frontend_type', ['select', 'radio', 'text', 'text_area']);
           $table->boolean('is_filterable')->default(0);
           $table->boolean('is_required')->default(0);

and another for values with something like this

	    $table->bigIncrements('id');
            $table->unsignedInteger('attribute_id');
            $table->foreign('attribute_id')->references('id')->on('attributes');
            $table->text('value');
            $table->decimal('price', 2)->nullable();
faisalsharif's avatar

i have same problem , please help , here is following structure

products
	id 
	name
	price
	sku
attributes
	id
	name
attributes_values
	id
	attribute_id
	value
product_attributes
	id
	product_id
	attribute_id
	value_id
class Product extends Model
{
	
}

class Attributes extends Model
{
	
}

class AttributesValue extends Model
{
	
}

i need following result in Lumen Laravel Framework

{
	id: 1
	name: Product A
	price: 20.00
	sku:000111
	attributes:[
		{
			name: Attribute A
			value: Attirbute Value A
		},
		{
			name: Attribute B
			value: Attirbute Value B
		}

	]
}

Please or to participate in this conversation.