[英]How to delete an item from array in Laravel Session?
I'm creating a cart system, this is my code to input some itens into the user 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'));
}
How can I delete an unique item from the users
array?如何从users
数组中删除唯一项?
It's able to remove the item from the users
array with the following code:可以使用以下代码从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'));
}
But I was searching for a clean way... Without remove the array and put it back to the Session...但我正在寻找一种干净的方法......无需删除数组并将其放回会话......
The following alternative has been found for a cleaner code:已找到以下替代方案以获得更清晰的代码:
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'));
}
Thanks to Kyslik for remind the dot notation...感谢Kyslik提醒点符号......
You can use forget()
or pull()
methods for that.您可以为此使用forget()
或pull()
方法。
$request->session()->forget('key');
The forget method will remove a piece of data from the session忘记方法将从会话中删除一条数据
$request->session()->pull('key', 'default');
The pull method will retrieve and delete an item from the session in a single statement pull 方法将在单个语句中从会话中检索和删除项目
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.