🥰Define Global Variable In Laravel (ok)

https://www.scratchcode.io/best-ways-to-define-global-variable-in-laravel/

01 Using Service Provider

C:\xampp8\htdocs\lva\app\Providers\AppServiceProvider.php

<?php
namespace App\Providers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
  /**
   * Register any application services.
   *
   * @return void
   */
  public function register()
  {
    //
  }
  /**
   * Bootstrap any application services.
   *
   * @return void
   */
  public function boot()
  {
    view()->composer('*', function ($view) {
      $view->with('user', Auth::user());
    });
  }
}

C:\xampp8\htdocs\lva\resources\views\welcome.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel</title>
  <!-- Fonts -->
  <link href="https://fonts.bunny.net/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
</head>
<body class="antialiased">
  <div
    class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
    @if (Route::has('login'))
    <div class="hidden fixed top-0 right-0 px-6 py-4 sm:block">
      @auth
      <a href="{{ url('/home') }}" class="text-sm text-gray-700 dark:text-gray-500 underline">Home</a>
      @else
      <a href="{{ route('login') }}" class="text-sm text-gray-700 dark:text-gray-500 underline">Log in</a>
      @if (Route::has('register'))
      <a href="{{ route('register') }}" class="ml-4 text-sm text-gray-700 dark:text-gray-500 underline">Register</a>
      @endif
      @endauth
    </div>
    @endif
  </div>
  @php
    echo '<pre>';
    var_export($user);
    echo '<pre>';
  @endphp
</body>
</html>

02 Using Traits xem bài viết dưới

03 Using Config File

C:\xampp8\htdocs\plugindev\routes\web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
  return view('welcome');
});
Route::get('user-roles', function () {
  dd(config('global.roles')); // Return all roles
});
Route::get('user-roles/super-admin', function () {
  dd(config('global.roles.super_admin')); // Specific role
});
Route::get('emails/dev', function () {
  dd(config('global.emails.dev')); // Specific dev email
});

C:\xampp8\htdocs\plugindev\config\global.php

<?php
return [
  'password' => [
    'super_admin' => env('SUPER_ADMIN_PASSWORD'),
    'admin' => env('ADMIN_PASSWORD'),
    'subscriber' => env('SUBSCRIBER_PASSWORD'),
    'client' => env('CLIENT_PASSWORD'),
  ],
  'roles' => [
    'super_admin' => 'Super Admin',
    'admin' => 'Admin',
    'subscriber' => 'Subscriber',
    'client' => 'Client',
  ],
  'twilio' => [
    'sid' => env('TWILIO_ACCOUNT_SID'),
    'token' => env('TWILIO_AUTH_TOKEN'),
    'phone_code' => env('PHONE_CODE'),
    'from' => env('TWILIO_FROM'),
  ],
  'emails' => [
    'dev' => env('DEV_EMAIL'),
  ]
];

C:\xampp8\htdocs\plugindev\resources\views\welcome.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel</title>
  <!-- Fonts -->
  <link href="https://fonts.bunny.net/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
  <!-- Styles -->
  
  <style>
    body {
      font-family: 'Nunito', sans-serif;
    }
  </style>
</head>
<body class="antialiased">
  {{dd(config('global.roles'))}}
</body>
</html>

01 Using Service Provider

Service providers in the laravel application are the central place where the application is bootstrapped. That is, laravel’s core services and our application’s services, classes, and their dependencies are injected into the service containers through providers.

Go to the app/Providers/AppServiceProvider.php and in boot()method add something like below:

<?php
 
class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Using view composer to set following variables globally
        view()->composer('*',function($view) {
            $view->with('user', Auth::user());
            $view->with('social', Social::all()); 
        });
    }
}

Now, $user & $social variables are available globally everywhere.

02 Using Traits

Traits allow us to develop a reusable piece of code and inject it into the controller and modal in a Laravel application. So we can define methods in traits and call the methods globally in Controllers, and Models, and then we can pass the data to the views as we want.

Create A Trait

To create Traits first create a Traits folder in app/Http, then create Traits/GlobalTrait.php file, then place the entire code in app/Http/Traits/GlobalTrait.php like below:

<?php
     
namespace App\Http\Traits;
 
use App\Models\Setting;
 
trait GlobalTrait {
 
    public function getAllSettings() 
    {
        // Fetch all the settings from the 'settings' table.
        $settings = Setting::all();
        return $settings;
    }
}

Use Traits In Laravel

We can call the traits by using use keyword followed by the Trait name eg. use GlobalTrait.

And we can easily call the method by using $this->methodName()that’s it. Check the example below:

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Http\Traits\GlobalTrait;
 
class HomeController extends Controller
{
    use GlobalTrait;
 
    public $settings;
 
    public function __construct()
    {
        $this->settings = $this->getAllSettings();
    }
}

03 Using Config File

In Laravel, you can create a file in the config folder and create variables in that and use that across the application. For example, if we want to store some information like user roles, emails, external APIs credentials, social links, etc.

Let’s create a new config file name global.php in config/ directory. We will also add some global variables into it and their values so that you can access those variables globally in the Laravel app. Let’s do it.

Create Global Config File

config/global.php

<?php
 
return [
    'password' => [
        'super_admin' => env('SUPER_ADMIN_PASSWORD'),
        'admin' => env('ADMIN_PASSWORD'),
        'subscriber' => env('SUBSCRIBER_PASSWORD'),
        'client' => env('CLIENT_PASSWORD'),
    ],
    'roles' => [
        'super_admin' => 'Super Admin',
        'admin' => 'Admin',
        'subscriber' => 'Subscriber',
        'client' => 'Client',
    ],
    'twilio' => [
        'sid' => env('TWILIO_ACCOUNT_SID'),
        'token' => env('TWILIO_AUTH_TOKEN'),
        'phone_code' => env('PHONE_CODE'),
        'from' => env('TWILIO_FROM'),
    ],
    'emails' => [
        'dev' => env('DEV_EMAIL'),
    ]
];

Use Global Variable

After defining variables in the config file, it’s time to call it from anywhere. You can easily get value using config() helper. Let’s call it from the test route as below:

routes/web.php

Route::get('user-roles', function() {
    dd(config('global.roles')); // Return all roles
});
 
Route::get('user-roles/super-admin', function() {
    dd(config('global.roles.super_admin')); // Specific role
});
 
Route::get('emails/dev', function() {
    dd(config('global.emails.dev')); // Specific dev email
});

Another way is to set the config on the go with key-value pair as below:

Config::set('social_links', $social_links);

And get the values using below:

Config::get('social_links');

Notes: Make sure you always run the php artisan config:clear command after adding or removing variable/values from the config file.

Additionally, read our guide:

That’s it from our end. We hope this article helped you how to define global variables in Laravel.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

Last updated

Was this helpful?