To demonstrate how to show database results on all views using of course view composer we’ll do a simple counter in our application. What that counter does is increments every time a specific form is submitted. let’s immediately get to it.

  1. we’ll need a migration file to do this we open our command window or Terminal that points of course to the application root and write:

php artisan make:migration test_Counters

on that migration file we’ll add what we want to do with it (dont forget to add the blow code to public function up(){) so in this case:

Schema::create('test_Counters', function (Blueprint $table) {

as you can see the Schema is very simple your can be much more complicated depending on what you want to do. don’t forget you have to do a:

php artisan migrate:refresh

to make sure you database is polluted, in this case you even have to add the first number to that database column you added with the schema.

2.  we’ll need a model, to make a model we simple add one again using our terminal and write:

php artisan make:model TestCounter

in my case we don’t have to write anything in it.

3. the Controller. You can create one or you can use an existing one where the submit button is going so in my case it’s TestController.php we’ll add the following code to it:


what this code does is go to the test_counters on the database and increments the test_counter column by one.  don’t forget to call:

use DB;

at the top of the controller in order to use the DB fasade

4. Providers, your AppServiceProvider.php file lets you to execute the code you want on all views.  so on the public function boot() methode you’ll need to add this:

\View::composer('*', function($view){
    $view->with('counter', testCounter::first());


What that code does is simply says allow the counter to be shown on all views.

5. show it, To show the results of our little counter we go to the app.blade.php page so the main layout page. All you have to do is add this to a place you want to show your results.

{{ $counter->test_counter }}

That’s it. now you can enjoy your counter.