Search code examples
laravel-4eloquentlaravel-5.1laravel-5

User, Cart and Products Eloquent Relationship


I would like to ask about the User, Cart and Product eloquent relationships. The User hasOne Cart and the Cart can have many Product.

class User {

    public function cart()
    {
        return $this->hasOne(App\Cart::class);
    }
}



class Cart {

    public function user()
    {
        return $this->belongsTo(App\User::class);
    }

    public function products()
    {
        return $this->hasMany(App\Product::class);
    }
}



class Product {

    //
}

I have database table structured like:

users

- id
- email
- username
- password

carts

- id
- user_id
- product_id
- quantity

products

- id
- name
- price

Is this correct?


Solution

  • No, it's not correct.

    users table is correct, but for carts table you shouldn't have product_id column because it's one to many relationship (cart can have multiple products), so your carts table should look like this:

    • id
    • user_id
    • quantity

    But looking further probably you don't want one to many relationship between cart and product, because probably products are common for all the users, so you need many to many relationship.

    So you should define one extra table (pivot table):

    cart_product

    - cart_id
    - product_id
    

    and you should change products relationship in Cart model like so:

    public function products() 
    {
      return $this->belongsToMany(\App\Product::class);
    }
    

    you should obviously create same reverse relationship for your Product model in case you need it.