Search code examples
phpmysqllaraveleloquentrelationships

Laravel: how to make a key of a column name?


I'm bending my mind for some time now over this problem. Could someone please help me?

I have two tables: products and product_attributes. The product has all basic product information and product_attributes has all specific information for products on different categories. It's much like the magenta attribute system. this table has 4 columns: id, product_id, attribute_name, attribute_value.

Now let's say a product has 2 attributes:

------------------------------------------------------
| id | product_id | attribute_name | attribute_value |
------------------------------------------------------
| 1  | 123        | length         | 123cm           |
------------------------------------------------------
| 2  | 123        | material       | Denim           |
------------------------------------------------------
| 3  | 123        | season         | Summer          |
------------------------------------------------------

Now if I set up the eloquent relationships and query a product, I get a product object with all three attributes. So far this is what I wanted. But now in a blade template I would like to be able to do something like this:

$product->attribute->length

Is this even possible or do I need to achieve these kind of things with a total different approach (like creating different tables for different product types/categories)?

Thanks in advance!


Solution

  • length is a tuple value not an attribute you need

    $product->attribute->where('attribute_name', 'length')
    

    or

    $product->attribute->whereAttributeName('length')