0
votes

I am developing simple e commerce website with laravel for learning purposes.

There are few things confusing me about database relations and inserting data to order-order_product tables when customer places an order.

User Migration:

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('address');
            $table->string('phone');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

User Model:

class User extends Authenticatable
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $attributes =[
     'street' => 'no adress entered',
     'city' => 'no city entered',
     'phone' => 'no phone'


    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function orderproduct(){        
        return $this->hasMany('App\OrderProduct');   
}
}

Orders Table:

 Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('customer_id')->unsigned();
            $table->foreign('customer_id')->references('id')->on('users');
            $table->string('name');
            $table->string('address');
            $table->string('phone');
            $table->date('order_date'); 

            $table->timestamps();
        });

Order Model:

class Order extends Model
{
   //Table Name

   protected $table = 'orders';

   //Primary Key

   public $primaryKey = 'id';

   //Timestamps

   public $timestamps =true;

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

public function orderproduct(){
    return $this->hasMany('App\OrderProduct');
}

}

Products Table:

Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('img');
            $table->string('name');
            $table->string('desc');
            $table->integer('quantity');//stokta kaç tane oldugu
            $table->integer('price');
            $table->timestamps();
        });

Product Model:

    class Product extends Model
{

    //Table Name

    protected $table = 'products';

    //Primary Key

    public $primaryKey = 'id';


    //Timestamps

    public $timestamps =true;

    public function orderproduct(){        
        return $this->belongsTo('App\OrderProduct');

    }
}

order_product Table:

 Schema::create('order_product', function (Blueprint $table) {
            $table->increments('id');
              $table->integer('order_id')->unsigned();
            $table->integer('product_id')->unsigned();
            $table->integer('quantity')->unsigned();
            $table->timestamps();

            $table->foreign('order_id')->references('id')->on('orders');
            $table->foreign('product_id')->references('id')->on('products');
        });

OrderProduct Model:

class OrderProduct extends Model
{

    //Table Name

    protected $table = 'order_product';

    //Primary Key

    public $primaryKey = 'id';


    //Timestamps

    public $timestamps =true;

public function order(){         
    return $this->belongsTo('App\Order');   

}
public function product(){
    return $this->hasMany('App\Product');   

}



}

I am using laravel session to hold cart data.Also i have a ordercontroller for storing order to database. The question is how do i insert correctly to order and order_product tables? First am i going to insert to orders then to order_product table ? For example if user has multiple items in his cart because product_id column in order_product table needs to be atomic i need to insert multiple rows. I can access product_id and their quantity from my cart but i couldnt manage to loop them properly and insert to db.

public function store(Request $request)
    {
        $oldCart = Session::get('cart'); 
        $cart = new Cart($oldCart);
//dd(arrays_keys($cart->items)); // returns ids of products in cart
//dd($cart->items[1]['qty']);      // returns quantity of item which has id 1



        $order = new Order;
        $order->name = $request->input('name');
        $order->address = $request->input('address');
        $order->phone = $request->input('phone');
        $order->customer_id = auth()->user()->id;

        $order->save();

        $orderProduct = new OrderProduct;

        //$orderProduct->product_id = ??  how to write in multiple rows if user has multiple items(so values will be atomic in product_id column)
        //$orderProduct->quantity= ??



    }
1
check your relation. 1- user has many orders, order belong to one user. 2- order has many products. product belong to many orders. 3- user has many product through order. you can add using create method that belong to model so you create new order then you use create method in order to create product. see documentation very clear laravel.com/docs/5.6/… - Mohd Alomar
You can use the relation to add related items. The create() method on a relation accepts multiple instances. - parker_codes

1 Answers

1
votes

Wrap them in transaction and insert them as usual:

DB::transaction(function() use($request) {

    $oldCart = Session::get('cart'); 
    $cart = new Cart($oldCart);

    $order = new Order;
    $order->name = $request->input('name');
    $order->address = $request->input('address');
    $order->phone = $request->input('phone');
    $order->customer_id = auth()->user()->id;
    $order->save();

    $orderProducts = [];
    foreach ($cart->items as $productId => $item) {
        $orderProducts[] = [
            'order_id' => $order->id,
            'product_id' => $productId
            'quantity' => $item['qty']
        ];
    }
    OrderProduct::insert($orderProducts);

});