Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 363
  • Last Modified:

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.
0
tjyoung
Asked:
tjyoung
  • 2
1 Solution
 
Julian HansenCommented:
array_push the latest item to the array
at the same time array_shift the first item out.
Example
$recent = $request->session()->get('recent');
if (!is_array($recent)) {
   $recent = array();
}
$recent[] = $id;
while (count($recent) > 3)) {
   array_shift($recent);
}
$request->session()->put('recent', $recent);

Open in new window

0
 
tjyoungAuthor Commented:
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);
0
 
Julian HansenCommented:
You are welcome - I was working off https://laravel.com/docs/5.3/session
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now