我目前正在做一个关于不同类型头发颜色的网上商店,但我现在有点问题。我正在开发一个按钮,该按钮会自动从会话文件中删除一个产品。为此,我正在使用一条$request->session()->forget('cart');
线。
这是我的控制器的样子:
public function index()
{
// Dit zorgt ervoor dat alle producten in het tabel Product-
// opgehaald worden en in de variabele $products gezet worden
$products = Product::all();
return view('winkelmand', compact('products'));
}
/**
* Show the form for creating a new resource.
*
* @return void
*/
public function create()
{
return false;
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return Application|Factory|View
*/
public function store(Request $request)
{
$product = Product::find($request->id);
if (!$product) {
abort(404);
}
$id = $request->id;
$cart = session()->get('cart');
// Als het winkelwagendje leeg is, dan is dit het eerste product
if (!$cart) {
$cart = [
$id => [
"name" => $product->name,
"description" => $product->description,
"price" => $product->price,
"quantity" => 1
]
];
session()->put('cart', $cart);
return view('winkelmand');
}
// Als het product al bestaat, dan de quantiteit verhogen met 1
if (isset($cart[$id])) {
$cart[$id]['quantity']++;
session()->put('cart', $cart);
return view('winkelmand');
}
// Als het product niet bestaat dan toevoegen met quantiteit = 1
$cart[$id] = [
"name" => $product->name,
"price" => $product->price,
"description" => $product->description,
"quantity" => 1
];
session()->put('cart', $cart);
return view('winkelmand');
}
/**
* Display the specified resource.
*
* @param Request $request
* @param int $id
* @return Application|Factory|View
*/
public function show(Request $request, $id)
{
return false;
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
return false;
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* // * @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
if ($request->id && $request->quantity) {
$cart = session()->get('cart');
$cart[$request->id]["quantity"] = $request->quantity;
session()->put('cart', $cart);
session()->flash('success', 'Cart updated successfully');
}
}
/**
* Remove the specified resource from storage.
*
* // * @param int $id
* @return string
*/
public function destroy(Request $request)
{
//Deze functie moet ervoor zorgen dat er door middel van een knop de
// desbetreffende item verwijderd wordt uit het winkelwagentje.
// Deze functie werkt alleen nog niet en wordt dus niet gebruikt in de webshop
$request->session()->forget('cart');
dd('cart');
return view('winkelmand');
}
我使用表单和方法POST
向 HTML 添加了一个按钮:
<td>
<form action="/winkelmand/{{ $id }}" method="POST">
@csrf
<input name="_method" type="hidden" value="delete" />
<input type="submit" value="x" />
</form>
</td>
所以它应该从会话中检索一个特定的产品(从按下的任何产品按钮),然后它应该从会话中忘记该键。
任何人都可以帮助我吗?
附言。对不起我的词汇量。