vendredi 30 octobre 2015

Laravel 5.1 - How view()->share works?

I am developing a web application where the footer lists latest and most popular posts. I also use this data at some other places as well (for e.g. homepage slider shows popular posts etc).

I tried exposing this data to all my views via view()->composer and also tried via view()->share from boot() method in AppServiceProvider.php

This is my code via view()->composer

public function boot()
{
    view()->composer('*', function ($view) {
                $popular = Post::with('likedby')->published()->get()
                          ->sortByDesc(function($item){ 
                                      return $item->likedby->count();
                           })->take(4);

                $popular->load('comment');

                $latest = Post::orderBy('created_at','desc')
                          ->published()->get()->take(4);

                $latest->load('comment','likedby');


                $view->with(compact('popular','latest'));

    });

}

This is my code via view()->share

public function boot()
{
    $popular = Post::with('likedby')->published()->get()
                              ->sortByDesc(function($item){ 
                                          return $item->likedby->count();
                               })->take(4);

    $popular->load('comment');

    $latest = Post::orderBy('created_at','desc')
                         ->published()->get()->take(4);

    $latest->load('comment','likedby');


    view()->share(compact('popular','latest'));
}

Basically, the queries are same.

I listen to the query event in routes.php

Event::listen('illuminate.query', function($query)
{
    var_dump($query);
});

I understood how view()->composer works - it basically run the callback function on every view [infact it calls the function multiple times if there are subviews e.g. @include('comments.list') ]

However, view()->share didn't show any queries, I am guessing that it got executed before I registered to listen for query events (in routes.php).

So, how view()->share really works and when it is called if I put it in boot() of AppServiceProvider.php? Are these variables stored as global variables?

Is there a way to listen to the query event in this case so I can properly test caching?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire