Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Global view data for all actions in Laravel Blade

Laravel’s Blade is a great templating system that blends with Laravel’s ecosystem very well. Setting some data to the view is a breeze and rendering those data into the template is ever so easy. For instance, if you would like to share some data from a controller’s action to a view, you’d do like so.

class HomeController extends BaseController
{
    public function __construct()
    {
       parent::__construct();
    }

    public function index()
    {
      return view('greetings', ['name' => 'Victoria']);
    }
}

In the above example, a $name variable is available to be rendered in a blade template greetings.blade.php. You can pass around a lot more data similarly but you got the idea.

But what if you want to share some data across all controller actions? Read on to find out.

Using View::share for sharing data

In order to share common data across each view of the controller’s actions, you can use the Illuminate\Support\Facades\View facade’s share method by establishing a key-value pair like so which can then be accessible across all the actions’ views.

use Illuminate\Support\Facades\View;

class HomeController extends BaseController
{
    public function __construct()
    {
       parent::__construct();

       View::share('common_data', [
         'foo' => 'bar'
        ]);
    }

    public function index()
    {
      return view('index');
    }

    public function show()
    {
      return view('show');
    }
}

As you can see here, the $common_data will be available to each view, both index.blade.php and show.blade.php alike.

This is useful in scenarios for example there are menu items which are common across a particular set of actions and you don’t want to repeat the code over and over again.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?