Background output of "View Composer"

19.04.2021 | 1005 | SQL

Background output of dynamic information on all pages

View Composers will be useful when some data is shared for many or all pages. Examples: navigation or a block with popular articles, etc. It is for such cases that Laravel provides an elegant solution. Also, a good point for performance is that without visual output, the compositor code also does not work. Let's create a template for the output:
resources/views/layouts/sidebar.blade.php
Let's add the code for the output of articles
@foreach ($articles as $article)
{{ $article->active_from }}
{{ $article->code }}
{{ $article->name }}
@endforeach
Let's call the template in the general website template (or any other):
...
@include('layouts.articles')
...
Add the provider to the "providers" array of the configuration file "config/app.php ":
...

'providers' => [
...
AppProvidersComposerServiceProvider::class,
],
...
Creating a provider:
app/Providers/ComposerServiceProvider.php
Adding our new View Composer to it:
namespace AppProviders;

use IlluminateSupportFacadesView;
use IlluminateSupportServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
public function register()
{
}

public function boot()
{
View::composer(
'layouts.sidebar',
'AppHttpViewComposersShowSideBar'
);
}
}
Creating View Composers:
app/Http/ViewComposers/ShowSideBar.php
We add the code for getting articles to it:
namespace AppHttpViewComposers;

use App;
use AppModelsArticle;
use IlluminateViewView;

class ShowSideBar
{
public function compose(View $view)
{
$articles = Article::where('active', 1)
->orderBy('date')
->take(10)
->get();

return $view->with(['articles' => $articles]);
}
}
Now on every page of the site you should see a list of articles and you don't need to repeat getting it in the page controllers.


← Back

Comments (0)