Link to home
Start Free TrialLog in
Avatar of tjyoung
tjyoung

asked on

Keeping only the last 3 items in Session array Laravel

Hi,
I'm using Laravel and keeping track of recently viewed item ID's in a 'recent' array.
To store them I use: Session::push('recent', $id) when a user visits an item details page.

After visiting a few items, my array when dumped looks like:
array:6 [▼
  0 => "17918"
  1 => "18204"
  2 => "17180"
  3 => "18119"
  4 => "17897"
  5 => "18119"
]

I'm only after the last 3 items (just showing last 3 items you visited). How can I store just the last 3 all the time instead of continually adding to the array? I thought I could just 'use' the last 3 items in the array but as a user continues to visit detail pages, the array will just keep getting larger. I was thinking array_slice perhaps to keep it to 3 but couldn't figure out how to implement in this case. Any suggestions/direction would be great.

Thanks as always.
PS: I'm nearly through this project and never would have made it without all the help I've received on this site. Thanks again.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tjyoung
tjyoung

ASKER

Minor changes for Laravel, but worked great. Thanks!
$recent = Session::get('recent');
      if (!is_array($recent)) {
               $recent = array();
            }
      $recent[] = $id;
      while (count($recent) > 3) {
            array_shift($recent);
      }
      Session::put('recent', $recent);
You are welcome - I was working off https://laravel.com/docs/5.3/session