How to define Global Variables for All Views in Laravel
In this tutorial, we will learn How to define Global Variables for All Views in Laravel. If Are you looking for an example of defining global variables for all views In Laravel? Define Global Variable for All Views Developers don’t want to write code again and again. I would like to show you the global variable for all views in Laravel. I will explain simply about defining global variables for all controllers and views Laravel. If you have a question about how to define a global variable for all view files in Laravel then you are right place and I will give a simple example. Also, You can use this example with Laravel 6, Laravel 7, Laravel 8, and Laravel 9 versions.
I’m working on big web applications and I need to define theme layout a global variable for all views in Laravel. So, I will show you how to define a global variable in this project. Laravel default provides AppServiceProvider
to define global variables for all blade files.
How to define Global Variable for All Views in Laravel
<?php #app/Providers/AppServiceProvider.php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Schema; 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() { Schema::defaultstringLength(191); View::share('project_title', Setting::where('key', 'project_title')->value('value')); View::share('project_sub_title', Setting::where('key', 'project_sub_title')->value('value')); } }
resources/views/users/index.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>How to define Global Variables for All Views in Laravel</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
<div class="main_content_iner">
<h1>{{ $project_title }}</h1>
<h2>{{ $project_sub_title }}</h2>
</div>
</body>
</html>