Delete items from Laravel Session array Delete items from Laravel Session array laravel laravel

Delete items from Laravel Session array


When you call Session::forget('event_data_display')[$index], there is no point at which that $index variable gets passed into the forget() method. So Laravel won't see it, and will unset the entire 'event_data_display' index of the Session array.

To unset the value at that index, you'll probably need to do something like this:

$event_data_display = Session::get('event_date_display');unset($event_data_display[$index]);Session::set('event_data_display', $event_data_display);

Laravel's Session does support adding to arrays via a specified index like this:

Session::push('user.teams', 'developers');

So you might also be able to access that index of the array like so:

Session::forget('event_data_display.' . $i);

I haven't tried it but it's worth a shot.

When you call Session::get('event_data_display')[$i], the reason that works is because PHP retrieves the array value from Session::get('event_data_display') before it looks for the value stored at the $i index.

When you call Session::forget('event_data_display'), the forget() method can only act on what is passed to it.


I solve it using the following code. Just pass the value that you want to delete in the array as an "id" to your controller like the code bellow

public function removeAddTocart(Request $request){    $remove = ''.$request->id.'';    if (Session::has('productCart'))    {        foreach (Session::get('productCart') as $key => $value)         {            if ($value === $remove)            {                Session::pull('productCart.'.$key); // retrieving the value and remove it from the array                break;            }        }    }}


Add

session()->save();

after clearing the session. Then only the values in session get deleted.