0

In one of my middleware I have used something like this

    $user = [ 
    'name' => 'noob',
    'phone' => '87548154'
   ]; /* which actually comes from redis cache */


    $request->attributes->set('user', $user);

and in the controller i use it like

$request->get('user')['name'] 

OR

$request->get('user')['phone'] 

As this seems very flexible, I would like to attach more data into the $user array. In the laravel docs its written above the get() method of Request class is

 * Gets a "parameter" value from any bag.
 * This method is mainly useful for libraries that want to provide some flexibility. If you don't need the
 * flexibility in controllers, it is better to explicitly get request parameters from the appropriate
 * public property instead (attributes, query, request).
 * Order of precedence: PATH (routing placeholders or custom attributes), GET, BODY

My question is, is it going to be a good idea? because the most frequently used data is already attached in the middleware. So that I dont have to write extra codes in the controller methods again and again. Will it affect on performance for a high traffic server?

Noob Coder
  • 2,816
  • 8
  • 36
  • 61
  • why not share it across all views inside the `AppServiceProvider`? – GabMic Mar 15 '18 at 09:55
  • Whats the purpose? You can use [view composer](https://laravel.com/docs/5.6/views#view-composers) to share data to views. – Kyslik Mar 15 '18 at 10:19
  • you are doing like `b = a` and `c =b` to get `a` to `c` , where you can directly access `c = a`. This would definitely but not significantly affect the perfomane. **You can use global variables in config.** – iamab.in Mar 15 '18 at 10:49
  • its a lumen project.. no views – Noob Coder Mar 15 '18 at 11:24

1 Answers1

0

I personnally never work this way. You can access the current user from anywhere using the Auth facade as following :

\Auth::user()

It enable you to never send it when unnecessary and still use it from anywhere (controllers, models, blades or everything else).

Then to access your properties :

\Auth::user()->phone

and so on...

kevinniel
  • 1,088
  • 1
  • 6
  • 14
  • Even better IMHO is `auth()->user();`, where `auth()` is "global" function and takes parameter (`$guard`) as well. – Kyslik Mar 15 '18 at 10:11
  • Not a trick see this https://github.com/laravel/framework/blob/56a58e0fa3d845bb992d7c64ac9bb6d0c24b745a/src/Illuminate/Foundation/helpers.php have fun! – Kyslik Mar 15 '18 at 12:35