phplaraveleloquent

How can I insert multiple children along with parent record using Laravel Eloquent


I am trying to create a simple shopping application using Laravel, I am using LaravelShoppingCart plugin to store items in the user session. When the user hits my store method the order and order_line records should be stored.

I am currently getting this error with the code below:

Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given, called in /home/vagrant/site/app/Http/Controllers/BasketController.php on line 130 and defined

Table schema:

// create orders table
Schema::create('orders', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned()->nullable();
    $table->text('order_notes')->nullable();
    $table->decimal('subtotal', 5, 2)->default(0);
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users');
});

// create order lines table
Schema::create('order_lines', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('order_id')->unsigned();
    $table->integer('menu_item_id')->unsigned();
    $table->decimal('sale_price', 5, 2);
    $table->integer('quantity');
    $table->timestamps();

    $table->foreign('menu_item_id')->references('id')->on('menu_item');
    $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
});

Order Model (relationship):

/**
 * Define relationship to OrderLines
 * @return [type] [description]
 */
public function order_line() {
    return $this->hasMany('App\OrderLine');
}

OrderLine Model (relationship):

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

Store Function:

public function store(CreateOrderGuestRequest $request) {    
    $order = new Order;

    $order->order_notes = $request->order_notes;
    $order->save();

    $order_lines = new Collection();

    foreach (Cart::content() as $row) {
        $order_lines->push([
            'menu_item_id' => $row->id,
            'quanity'      => $row->qty,
            'sale_price'   => $row->price
        ]);
    }

    $order->order_line()->saveMany(new OrderLine($order_lines));

    // redirect somewhere after        
}

Solution

  • You were pretty close. You just need to make a few adjustments to get this to work. You need to pass a collection of models or an array of models to the saveMany method so when you loop through, instead of "pushing" an array, "push" a new OrderLine model like this:

    foreach (Cart::content() as $row) {
        $order_lines->push(
            new OrderLine([
                'menu_item_id' => $row->id,
                'quanity'      => $row->qty,
                'sale_price'   => $row->price
            ])
        );
    }
    

    Then, when you call saveMany, just pass the $order_lines collection;

    $order->order_line()->saveMany($order_lines);
    

    This, of course, is assuming Cart::content() is valid.

    On a related note: saveMany will not insert all the entries with a single query. It'll loop through and add them one-by-one. To do a bulk insert with just a single query, you need to use the query builder.

    Edit: An example of how to use the insert method using the query builder:

    $order_lines = [];
    
    foreach (Cart::content() as $row) {
        $order_lines[] = [
            'menu_item_id' => $row->id,
            'quanity'      => $row->qty,
            'sale_price'   => $row->price,
            'order_id'     => $order->id
        ];
    }
    
    DB::table('order_lines')->insert($order_lines);
    

    You just build an array of data to insert into the table and insert it.