Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RafaelMunoznl's avatar

Pass a collection of objects between Controllers through the session

May problem is as follows:

  • I have a list of items in a view index.blade.php.

  • I am saving a new Item in the database and redirecting back to the same view.

  • This process could be repeated as much as the user needs. Save, back, save again, back and so on.

  • Now, back to the index view, I want to show the items on the top, apart from the rest.

This process could be repeated so at the top I am getting a new list with the Items created in the session.

That said, it seems I need to create an array of Items in which the second part of the pair is an object ['key', $object]

I did this:

The store method:


public function store(ItemRequest $request)
{
	// other code here
	$newItem = $this->ItemRepository->createItem($request);

	$request->session()->put(['newItem', $newItem]);

	return redirect()->back();
}

In the index method:

   public function index()
    {
	// other code...
		
        $items = $request->session()->pull('items');

        return view('frontend.search.results', compact('items', // other variables here));

    }

In the view results.blade.php

@foreach($items as $key => $item)
	<h4>{{$item->name}}</h4>
	
	<p>{{ $item->price }} </p>
	<p>{{ $item->quantity }} </p>
	<p>{{ $item->unit }} </p>
@endforeach

Unfortunatelly, it does not work. It is the first time I use the session for such a thing. I am not eve sure is the session could be used for that. Reading the documentation did not help me really

Could anybody explain me what am I doing wrong? How do I pass that variables (collection) back to the previous view?

0 likes
4 replies
MichalOravec's avatar

@rafaelmunoznl Why you don't want to get it from database? And just sort it and limit it.

$items = Item::latest()->limit(10)->get();
RafaelMunoznl's avatar

@michaloravec It is certainly an easier solution, but it would mean I have always that list on top.

The idea was just to show the user the new items that he has just created.

P.S. But I think that I could select the itens ```where('created_at', $today). I'll think about it.

ekpono's avatar

The session key is wrong

$request->session()->put(['newItem', $newItem]);

change it to

$request->session()->put(['items', $newItem]);

MichalOravec's avatar

@rafaelmunoznl Or just save ids to session not whole objects.

Then just use

$items = Item::latest()->whereIn('id', $idsFromSession)->get();

Please or to participate in this conversation.