Thursday, April 14, 2016

Laravel Share Some Variable with All Views

Hello,

Recently in one of my laravel project we have a requirement create side menu in app with some dynamic stats numbers like

Users   (12)
Managers  (10)
Questions  (25)

This menu is included in all the views and to set dynamic values in that we have to share this numbers globally. In this blog I am going to mention how to so this.

1) Create a BaseController class and extend it with controller and add a constructor.

class BaseController extends Controller {
       public function __construct() {
     
       }
}

2) Inside that constructor get all the numbers and share it with view

$users = DB::table('users')->count();
$managers = DB::table('managers')->count();
$questions = DB::table('questions')->count();

View::share('users',$users);
View::share('managers',$managers);
View::share('questions',$questions);

after adding this code your base controller should look like following.

class BaseController extends Controller {
       public function __construct() {
             $users = DB::table('users')->count();
             $managers = DB::table('managers')->count();
             $questions = DB::table('questions')->count();

            View::share('users',$users);
            View::share('managers',$managers);
            View::share('questions',$questions);
       }
}


3) Now extend this base controller to all other controllers.

class MyConttoller extends BaseController {

}

That's it now any view which you render from controller will have those variables by default. Now you just have to use those variables in views.

<ul>
       <li> Users  ({{$users}}) <li/>
       <li> Managers  ({{$managers}}) <li/>
       <li> Questions  ({{$questions}}) <li/>
<ul/>

Hope this helps you.


No comments:

Post a Comment