Home / Snippets / How to easily pass data to all views in Laravel 8?
How to easily pass data to all views in Laravel 8? cover

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

2.1K

2 years ago

0 comments

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

notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this