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

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
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);
Julian Hansen

You are welcome - I was working off https://laravel.com/docs/5.3/session
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23