How to Sharing Data with all Views ?



How to Sharing Data with all Views ?..

Answer / nafees ahmad

We have seen how we can pass data to views but at times, there is a need to pass data to all the views.
Laravel makes this simpler, There is a method called share() which can be used for this purpose.
The share() method will take two arguments, key and value.
Typically share() method can be called from boot method of service provider.
We can use any service provider, AppServiceProvider or our own service provider.
Example :
Observe the following example to understand more about sharing data with all views -

Add the following line in app/Http/routes.php file.
app/Http/routes.php

Route::get('/test', function(){
return view('test');
});

Route::get('/test2', function(){
return view('test2');
});
Step 2 - Create two view files — test.php and test2.php with the same code. These are the two files which will share data. Copy the following code in both the files. resources/views/test.php & resources/views/test2.php
<html>
<body>
<h1><?php echo $name; ?></h1>
</body>
</html>
Step 3 - Change the code of boot method in the file app/Providers/AppServiceProvider.php as shown below.

(Here, we have used share method and the data that we have passed will be shared with all the views.) app/Providers/AppServiceProvider.php

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Laravel PHP Framework Interview Questions

How can you reduce memory usage in laravel?

0 Answers  


What is laravel language?

0 Answers  


What is eloquent orm?

0 Answers  


How to create a laravel project using composer.

0 Answers  


How can you write your own service provider in laravel.

0 Answers  






How to serve sites with tls on valet?

0 Answers  


Where can I learn laravel?

0 Answers  


Tell me what is official website url of laravel?

0 Answers  


Is laravel based on symfony?

0 Answers  


What is rate limiting?

0 Answers  


How to get JSON Response on Laravel ?

1 Answers  


How do I make my application serve its content in different languages?

0 Answers  


Categories