How to Pass Data to All Views using Composer Share in Laravel?
Hey Guys,
In this tutorial, you will learn laravel global variable using composer. If you have a question about laravel global view variables then I will give a simple example with a solution. if you want to see an example of laravel view composer share variable then you are in the right place. We will use laravel pass data to view composer.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.
Sometimes we work on big web applications and you need to define a global variable for all views in laravel then how you will do that?, I will show you how to define a global variable for all views in laravel. laravel provides AppServiceProvider to define global variables for all blade files. so, let's see the simple example code:
Define Global Variables for All Views
app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;
use App\Models\Setting;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
view()->share('theme', 'admin.layout');
view()->share('projectTitle', Setting::where('name', 'project_title')->value('value'));
}
}
Use Global Variables in Blade File
resources/views/demo.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h1>{{ $projectTitle }}</h1>
<h2>{{ $theme }}</h2>
</body>
</html>
Output:
You can see the below output:
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Datatables Date Range Filter Example
- Laravel Route Pass Multiple Parameters Example
- Laravel Blade Check if Array Key Exists Example
- How to Update Multiple Records in Laravel?
- How to Get Browser Name and Version in Laravel?
- Laravel React JS Form Validation Example
- How to Store Array in Database Laravel?
- Laravel Google ReCaptcha V2 Example Tutorial
- Laravel Send an Email on Error Exceptions Tutorial
- How to Add Google Map in Laravel?
- Laravel Firebase Push Notification to Android and IOS App Example
- How to Get Config Variable Value in Laravel?
- How to Define Global Variables in Laravel?