Laravel

How to share Variable with all Views in Laravel?

January 30, 2018

author:

How to share Variable with all Views in Laravel?

We took a good look at how to pass data to views in the last section, but then what if you have a situation where you need to pass data to all the views? For instance, you have multiple UI options and you utilize them as per users’ geolocation. In such cases, you have to let your Laravel views know user’s current location in some way.

Laravel makes such use cases really easy. We can achieve this with Laravel view facade’s share method. Confused? Well, don’t be!

# Create Route

Lets us create two fresh routes:

# routes/web.php
...
Route::get('admin', function () {
    return view('admin');
});

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

# Create Blade View

Next, create two fresh views:

# resources/views/admin.blade.php

<html>
  <body>
    <h1>Admin Page</h1>
    <p><?= $someKey ?></p>
  </body>
</html>
# resources/views/user.blade.php

<html>
  <body>
    <h1>User Page</h1>
    <p><?= $someKey ?></p>
  </body>
</html>

# Share Variables

We have discussed enough regarding the above process so let us now start putting shared data in place. To do so, add following code in app/Providers/AppServiceProvider:

# app/Providers/AppServiceProvider.php

public function boot()
{
   // add this
    view()->share('someKey', 'This is shared data');
}

# Testing

We just added a key-value pair to share in all our views. And we can test this with:

localhost:8000/admin
Laravel Sharing data in views
localhost:8000/user
Laravel Sharing data in views

Conclusion
Hope you’re enjoying learning Laravel and understanding how clean the coding can get in this framework. If you still feel overwhelmed with all the logic and syntax, pause a bit, go back and revise everything up till now. If not, brace yourself, we are above to simplify the views even more with an introduction to blade templating.

Questions & Comments:

Thank you for reading. Hope this article about sharing data with multiple views simultanoeusly was useful. Got any questions? Post them in the comment section below.

Leave a comment

Your email address will not be published. Required fields are marked *