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

johnw65's avatar

Drop Down Menu - Keep it the same for the duration of the session

After a successful login, I want the user to able to have access to a drop down menu which is generated using a query builder. The drop down menu will not change so I do not want to query again. So until the user logs out, the content of the drop down menu will remain the same. I'm thinking about creating a partial view so it will be on top the screen. So what is the best approach. Thanks.

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

One solution would be to store the query result in a session variable and use it to generate the drop down menu. Here's an example implementation in Laravel:

  1. In your login controller, retrieve the query result and store it in a session variable:
// Retrieve the query result
$menuItems = DB::table('menu_items')->get();

// Store it in a session variable
session(['menuItems' => $menuItems]);
  1. In your view, check if the session variable exists and use it to generate the drop down menu:
@if(session()->has('menuItems'))
    <select>
        @foreach(session('menuItems') as $menuItem)
            <option value="{{ $menuItem->id }}">{{ $menuItem->name }}</option>
        @endforeach
    </select>
@endif
  1. To ensure that the session variable is cleared when the user logs out, add the following code to your logout controller:
session()->forget('menuItems');

This approach ensures that the query is only executed once per session, reducing unnecessary database queries.

Please or to participate in this conversation.