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

phpMick's avatar

Use session array to build menu?

Hi,

I have an array in my session, which contains the parts of the system my user can access.

Can I check this in a blade template? Then I can use it to determine if I should display a menu item or not?

ps The details are in the session because they are in a separate DB and I only want to hit it once.

Mick

0 likes
3 replies
phpMick's avatar

Looks like I can do this:

@foreach(Session::get('objects') as $object)
    {{$object}}
@endforeach

But, that makes it hard to control where they appear.

I really want to do in_array....

Any ideas?

andremellow's avatar
Level 9

@phpMick , I don't know what is your session "objects" structure.

Any way, I don't like to you "Session" direct in the view, but it works.

What I do, store the "keys" of features that user can access, them I pass the @loggedUser to view, and access it by calling a method in User.php

//in your main controller 
abstract class Controller extends BaseController
{
   use DispatchesJobs, ValidatesRequests;

   protected $user;

   function __construct() 
   {
       $this->user = AUTH::user();
       View::share( 'loggedUser' ,  $this->user );

   }

   
}

//now in you view you can do like

@if( $loggedUser->canDo('key') 
    <a href="#">feature 1</a
@endif 
@if( $loggedUser->canDo('key1') 
    <a href="#">feature 2</a
@endif 
//In your User.php
 
public function canDo($key)
{
    $keys = Session::get('objects');

    return in_array( $key ,  $keys );
}


`` `
phpMick's avatar

That is amazing! Feels a million times better.

Many thanks.

Mick

Please or to participate in this conversation.