我正在创建一个购物车系统,这是我将一些itens输入用户Session的代码:
public function jsonResponse($data){
return response()->json([
'success' => true,
'users' => $data
]);
}
public function post(Request $request ,User $user)
{
$request->session()->push('users', $user);
return $this->jsonResponse($request->session()->get('users'));
}
如何删除users
数组中的唯一项?
可以使用以下代码从users
数组中删除该项:
public function delete(Request $request, User $user)
{
$users = $request->session()->get('users');
foreach ($users as $key => $val) {
if($user->id == $users[$key]->id){
$array = $request->session()->pull('users', []);
unset($array[$key]);
$request->session()->put('users', $array);
return $this->jsonResponse($request->session()->get('users'));
}
}
return $this->jsonResponse($request->session()->get('users'));
}
但我正在寻找一种干净的方式......不删除数组并将其放回会话......
为更清洁的代码找到了以下替代方案:
public function delete(Request $request, User $user)
{
$users = $request->session()->get('users');
foreach ($users as $key => $val) {
if($user->id == $users[$key]->id){
$request->session()->forget('users.'.$key);
return $this->jsonResponse($request->session()->get('users'));
}
}
return $this->jsonResponse($request->session()->get('users'));
}
感谢Kyslik提醒点符号......