我有商店网站。我想将OrderController和PanelCotroller数据与我的Model Order中的最后一个orderId进行分享。这是我的代码:
class OrderController extends Controller
{
private $errors = [];
public function addOrder()
{
if (!Auth::check()) {
$this->errors[] = 'error';
return redirect()->back()->with('errors', $this->errors);
}
$userId = Auth::id();
$order = new Order();
$isOrdered = $order->addOrder($userId, $this->cart);
if ($isOrdered){
return redirect('panel')->with('info', 'Everything fine');
}
}
}
现在我的函数addOrder返回true或false。当我调用函数getOrderId时,我可以在OrderController上看到orderId。但是我想在PanelController中调用getOrderId - mainSite动作。当我从Order创建对象时,我的函数getOrderId返回null ...
class Order extends Model
{
protected $table = 'orders';
public $timestamps = false;
private $orderId;
public function addOrder($userId, Cart $cart)
{
$order = new Order();
$order->user_id = $userId;
$order->save();
foreach ($cart->getItems() as $cartProduct) {
$orderProducts = new OrderProduct();
$orderProducts->product_id = $cartProduct->getProduct()->id;
$orderProducts->order_id = $order->id;
$orderProducts->quantity = $cartProduct->getQuantity();
$orderProducts->price = $cartProduct->getProduct()->price;
$orderProducts->save();
}
$cart->clear();
$this->orderId = $order->id;
return true;
}
public function getOrderId()
{
return $this->orderId;
}
}
这是我的PanelController。
类PanelController扩展Controller {
public function mainSite()
{
if (Auth::check()) {
$order = new Order();
$order -> getOrderId() <---- here return me null instead my
last OrderId.
return View("panel");
} else {
return redirect('/login');
}
}
如何对我的变量orderId或方法执行getOrderId对所有控制器都可见?
答案 0 :(得分:2)
有两种方法可以在其他控制器中获取值 -
BaseController
中设置值并将其扩展到您想要的任何位置。我更喜欢第二种方法。
答案 1 :(得分:1)
创建订单后,将ID添加到会话中。然后在PanelController中,您可以从会话中获取ID。
OrderController:
$order = new Order();
$isOrdered = $order->addOrder($userId, $this->cart);
session(['orderid' => $order->id]);
PanelController:
if (session()->has('orderid'))
$order = Order::find(session('orderid'));
else
dd('No order id found in session!');