ReynierPM ReynierPM - 6 months ago 8
PHP Question

Get information from database and output to the view just one|first time

I am trying to get out some information from the database, filter that information based on logged in user and then return the proper information to the view for built a menu based on user groups|roles|permissions.

This should only happen once and right after the user login in the application. For the menu I am using this package and for the user/groups/permissions I'm using Cartalyst Sentinel.

I could use a

Middleware
but I think its purpose is not to get information from the DB and build some output or a
View Composers
but I don't want this to be executed all the time when layout or header is called which is almost all the time or all the time I would say or I can use a
Service Provider
I don't know to much about this latest.

So having this information: what would you do in this case? how would you built the menu and output to the
layout
or
section@header
?

Answer

Here is a simple exemple

Lets suppose that you want to retrieve a user with his roles and cache the results

public function test() {
//getting authenticated user with roles
$userwithroles = Cache::remember('users-'.Auth::user()->id, 60, function() {
return User::with('roles')->where('id', Auth::user()->id)->get();
});
  return View('home')->with('$data',$userwithroles);
}

Now, the query will be executed only every one hour , you can look at the laravel docs to learn more tricks and cool other stuff

Caching in laravel

You can also check this Video (its laravel 4 but its almost the same)

I hope this might help