我正在尝试将(订单编号,产品编号和数量)存储在数据库的Order Product table
中,因此在下订单时应将orders
和order product
存储在数据库中。但是现在它仅存储订单并给出此错误"Trying to get property of non-object"
。
我尝试了其他来源的一些解决方案,但仍然无法正常工作。
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');
}
}
已更新:
我现在更改了代码,它显示了数量,但不能显示product_id,它显示了错误"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'],
]);