Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize data sharing among multiple views in Laravel 5

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report