ItSolutionStuff.com

Laravel Global Variable for All Views Example

By Hardik Savani • April 16, 2024
Laravel

Hey,

Are you looking for an example of laravel global variable for all views. If you have a question about laravel global variable for all blade files then I will give a simple example with a solution. I would like to show you global variable for all views in laravel. I explained simply about global variable for all controller and views laravel.

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...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Pass Data from Controller to View in Laravel?

Read Now →

Laravel Blade Check If Variable Exists or Not Example

Read Now →

How to use Carbon in Laravel Blade or Controller File?

Read Now →

How to Call Controller Function in Blade Laravel?

Read Now →

Laravel Blade @includeWhen and @includeUnless Example

Read Now →

Laravel Blade Include File If Exists Example

Read Now →

Laravel Include Blade File with Data Example

Read Now →

Laravel Blade Include File Example

Read Now →

Laravel - How to Check If Array is Empty in Blade?

Read Now →

Laravel Clear Cache of Route, View, Config Command

Read Now →

Laravel - How to Get .env Variable in Blade or Controller?

Read Now →

How to use Inject View in Laravel?

Read Now →

Laravel Ajax Render View With Data Example

Read Now →

Laravel Blade Check if View Exists or Not Example

Read Now →