Using View composer and cache to solve side bar and caching.

When you designed the site, maybe it include side bar(maybe recent posts or others),You maybe to do like this:

For sure, your blade file will be:

Here is a problem, if you need to same “side bar with posts”, you should do the same for this:

If you need side bar with posts, you need put $posts and get all posts anywhere, that doesn’t make sense, so you need using view composer to compose side bar.

So, how to use it? here is a simple example.

firstly, you need make a new provider on your application, in official reference, you need create ComposerServiceProvider , whatever you can use you want name.

secondly, you need to write some code to tell laravel: “hey! I need this to compose to a specific view render.”

Looks good! For now, we have to write something at blade and clear our controller.

Our blade you can modified to:

Maybe you have some problems: How to bind data to this? that will be get errors! Just scroll up and see ComposerServiceProvider , we have been bind data for specific blade render: collections.index, so you don’t worry about that. For now, just finish our job:

Notice: you should add ComposerServiceProvider to app.php providers, tell laravel you need to register this provider.

That’s amazing! you don’t compact any data to blade in controller, but still got same things.

If you need cache this, just follow laravel cache documentation, like this:

that’s will work nicer.

Hold on! I think that’s bad at ComposerServiceProvider ! all data and view render stick in together, looks so crowed.

You can use View composer and new a instance to make clearly.

And you should tell ComposerServiceProvider you will use this view composer instead of before.

Maybe you want all collection views bind this side bar.

View::composer(‘collections.*’, \App\Http\ViewComposers\AllPostComposer::class); //support wildcard.

or specific views:

View::composer([
‘collections.index’
‘collections.show’
], \App\Http\ViewComposers\AllPostComposer::class);

Composer vs. Creator

Composer you can’t change variables in controller.

Creator on the other hand, you can change variables in controller.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.