I am trying to get (order_id, product_id and quantity) to be stored in Order Product table
in database, so when placed an order it should store orders
and order product
in database . But now it only store orders and gives this error "Trying to get property of non-object"
.
I have tried some solutions from other sources but still not working.
CheckoutController
<?php
namespace App\Http\Controllers;
use App\Order;
use App\OrderProduct;
use Illuminate\Http\Request;
use cart;
class CheckoutController extends Controller
{
public function index()
{
return view('checkout');
}
public function create()
{
//
}
public function store(Request $request)
{
//Insert into orders table
$order = Order::create([
'user_id' => auth()->user() ? auth()->user()->id : null,
'shipping_email' => $request->email,
'shipping_name' => $request->name,
'shipping_city' => $request->city,
'shipping_phone' => $request->phone,
// 'error' => null,
]);
//Insert into order product table
$cart = session('cart');
foreach(session('cart') as $products) {
OrderProduct::create([
'order_id' => $order->id,
'product_id' => $products->id,
'quantity' => $products->quantity,
]);
}
$cart = session()->remove('cart');
return redirect()->route('confirmation.index')->with('success_message', 'Thank you! Your payment has been successfully accepted!');
}
public function show($id)
{
//
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
OrderProduct.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class OrderProduct extends Model
{
protected $table = 'order_product';
protected $fillable = ['order_id', 'product_id', 'quantity'];
}
Order.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = [
'user_id', 'shipping_email', 'shipping_name', 'shipping_city', 'shipping_phone',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('quantity');
}
}
Updated:
I have changed code now it shows quantity but can't show product_id it gives error "Trying to get property of non-object"
if ($order) {
foreach(session('cart') as $products) {
if (empty($products)) {
continue;
}
OrderProduct::create([
'order_id' => $order->id ?? null,
'product_id' => $products['id'], //-> This not working
'quantity' => $products['quantity'],
]);