0

I have a query which I use all over my routes.php under almost every get request and also use the results in many of my views. It makes more sense at this point for me to call the query once and be able to use it globally without ever having to call it again.

Here's the query:

$followers = Follower::where('user_id', '1')
    ->get();

How can I do this?

3 Answers3

1

Why not just execute the query once in an init function and store the result into a global variable?

global $followers = Follower::where('user_id', '1')
->get();
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

you can store it to the session every time the user logs in

Like this exemple

$followers = Follower::where('user_id', '1')
    ->first();
Session::put('followers', 'value');

whenever you want that you can access it like this

$value = Session::get('followers');
Achraf Khouadja
  • 6,119
  • 4
  • 27
  • 39
  • actualy that was in my mind , anything you feel comfortable with, that actually works is great, if you have some issues understanding the caching functionality , feel free to ask, good luck – Achraf Khouadja May 09 '16 at 02:46
0

The another answer with session is a simple solution but I would suggest you to use Laravel Cache for this purpose (because this is the standard practice).

The Laravel Cache::remember accepts three parameters.

  1. key: make an md5 key of 'followers' and 'user id'
  2. time: time in minutes you want to cache the values (depending how frequently your values will be changed)
  3. A closure function which runs when no value is found corresponding to the key. (this method will query once, in this case, and store the value in your cache)

Just do the following in your BaseController's constructor:

$id = 1; //User id
$key = md5('followers'.$id);
$minutes = 60; //cache for 1 hour, change it accordingly
$followers = Cache::remember($key, $minutes, function() use ($id) {
  return Follower::where('user_id', $id)->get();
});

Now of course to use Cache you need to use some Cache driver like Redis.

If you don't have how to setup it Read my other answer.

Though it may be little longer solution for your problem, and may take you 15-20 min to set up and run everything, but believe me once you start using cache you will love it.

Community
  • 1
  • 1
Abhishek
  • 3,900
  • 21
  • 42