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

SarnaMC's avatar

How to create a global variable

Hi! J'm working right now on some project and have a simple question. How to make global variable in laravel? J have UserController class, and i would like to create variable $User always on system start. and use this variable as global (every controller will use it). I've tried:

  1. Add to config/app.php to aliases, but I have no idea how it works

2.Create it manually (new [path]) in some autoloaded files - not working too

3.J saw solutions with binding but where to put this code?

I'd like to get a variable like $request

Thanks for help everyone

And sorry for my tragic language

0 likes
6 replies
topvillas's avatar

Create your own controlller than extends the base controller and get your controllers to extend that.

1 like
SarnaMC's avatar

@topvillas yea, that is an idea but i would like to load many many things in UserController constructor (load data from DB like name, permissions, notifications), so your idea is good but not in my case. $User variable has to be some kind of "Storage" to keep user info.

And for people who think it's a bad idea - every, EVERY page would use information stored in $User, because it will be an advanced system.

P.S. Caching information is not a good idea, because all information must be loaded dynamically

topvillas's avatar

How about creating a service and using that. A little bit over the top though, just to access a single global variable.

Or maybe going with the extending controller option I described but creating and using a trait that supplies your global user.

1 like
LaraStorm's avatar

use AppServiceProvider

app/Providers/AppServiceProvider.php

    public function boot()
    {
        view()->composer('app', function($view)
        {
            $brands = brand::where('isActive', '=', 'Yes')->orderby('name', 'ASC')->get();
            $view->with('brands', $brands);
        });
           
    }

1 like
martinbean's avatar

@SarnaMC Controllers are instantiated before the session is started (and authenticated user is resolved). Unfortunately, this means you will have to access the the user in each of your controller actions where you need it:

class SomeController extends Controller
{
    public function someAction(Request $request)
    {
        // You can access authenticated user via $request->user()
    }
}
1 like
SarnaMC's avatar

I did not expect so many answers, thank you guys!

@topvillas what do you think about extending UserController, but with static variables in it instead of normal? This should work...

@LaraStorm ok, J will try how this works

@martinbean yeea, J saw it before but maybe there is a simpler way, That's why I wrote here

Thank you one more time, As soon as I get back from work, I will test these solutions

Please or to participate in this conversation.