Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize data sharing among multiple views in Laravel 5

Shulou Source: shulou.com Published: 2022-06-02 06:37:18 09月24日 Update

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

Tags: Methods views data components multiple questions more help answers easy easy content variables just at the same time appearance examples guys buddies Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi OPPO Reno Redmi Shulou Tech Info Microsoft