How to realize data sharing among multiple views in Laravel 5
In order to solve the problem of how to share data among multiple views in Laravel 5, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
one
{{$cqh}}
Now the requirement is that every page will use this variable, how to share this data?
Generally, I will set this kind of operation in the boot method of the Laravel service. Here are two ways to share data.
Method 1: use the View:share method, such as in CqhServiceProvider
one
two
three
four
Public function boot ()
{
View::share ('cqh','chenqionghe')
}
This is using the appearance mode, or you can use the view () method directly
one
View ()-> share ('cqh',' chenqionghe')
Method 2: use the composer method to transfer data to the navigation.blade.php separately, as follows
one
two
three
four
five
six
Public function boot ()
{
View ()-> composer ('navigation', function ($view) {
$view- > with ('cqh','chenqionghe')
});
}
The above is done in the form of a closure, which, like routing, can also be replaced by a class, called a component in Laravel, as follows
one
two
three
four
Public function boot ()
{
View::composer ('navigation',' App\ Http\ ViewComposers\ MyViewComposer')
}
This registers the view component, and each time the navigation view is rendered, the MyViewComposer@compose will be executed.
Let's see how this component is defined.
one
two
three
four
five
six
seven
eight
nine