Posts Learn Components Snippets Categories Tags Tools new About
/

How to easily pass data to all views in Laravel 8?

Learn how to pass data to all views in Laravel 8 to allow data reusability across different blade views

Created on Nov 19, 2021

18 views

In this short snippet, you will learn how to pass data to all views in Laravel 8 so that it's accessible for all blade templates.

Method 1: Share via ‍boot function in AppServiceProvider


The first method is to share the variable via the "boot()" function in AppServiceProvider and by passing your data like the following it will be shared across all the views.
<?php // App\Providers\AppServiceProvider

public function boot()
{
  view()->share('key', 'value');
}

Method 2: View Composer


The next method is to use view composer and you can define your code like below. This will ensure that it's shared to all views "*" and the data that's being passed on for this example is the "posts"'.
<?php

view()
    ->composer('*', function ($view) {
        $posts = Post::take(10)->get();

        $view->with('posts', $posts);
    });

Other Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components
)