Caio Kawasaki Caio Kawasaki - 19 days ago 7
PHP Question

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?




Alternative 01



It's able to remove the item from the
users
array with the following code:

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...




Solution 01



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...

Answer

You can use forget() or pull() methods for that.

$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

Comments