简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM