We have talked about Laravel Framework so many times. It’s easy to use, flexible and fast. It’s true that, if you do not practice, you will never learn anything. As much as Laravel is amazing to use, it’s hard to master as well. In today’s tutorial, we will show you the tips and tricks about, how to share data to all views in laravel 5.2.
How to share data to all views ?
Imagine if you have an options table on you database that store all your application settings and you want to show it’s content to every view. So how you do that?
Laravel made it easy. One way and the most short and basic way to share data to all views is to use view:share(). Let see and example. The same above example, you have your options table in you database and you want to access its data in your master.blade.php page or any there view.
Our table structure for Options table in database looks like this:
id - int : auto-increment name - varchar : 50 value - varchar : 50
Open your AppServiceProvider.php which is under App/Providers direcory. Your code might look like this:
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Auth; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // } /** * Register any application services. * * @return void */ public function register() { // } }
Now, add the following codes. Make sure you add the use App\Option Model at the top
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Option; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { $companyName = Option::find(1); $copyRight = Option::find(2); view()->share('companyName', $companyName); view()->share('copyRight', $copyRight); } /** * Register any application services. * * @return void */ public function register() { // } }
Inside boot function we created two variable for two row in option table. the first one contain $companyname, and the second one is for $copyright. (if you have more, you can add more)
So, the view->share() will take two arguments. First one, a name to be accessible in views, and second the data that pass to views.
How to access data in views?
As I said, the first argument is the name that you can access the data with. So, in your view, just echo the variable. example
<p> {{$companyName}} </p> <!-- or --> <p> {{$copyRight}} </p>
Conclusion
So, that was it. Very easy and simple. There are some other says also that you can share data to all view like view composer. We will cover those topic in future tutorials. I hope it has been informative for you.
Hey thanks! it work for me.
good post)) thank you!
Hi, thank you for tutorial. Works like a charm!
That’s good. Thanks for feedback.
Hey thanks so much, i searched for many hours and nothing worked for me, only yours post really helped to me
You’re welcome. 🙂