Home » Best Ways To Define Global Variable In Laravel

Best Ways To Define Global Variable In Laravel

Last updated on May 17, 2022 by

In this tutorial, we will see how to define the global variable in Laravel. Usually, developers don’t want to write code again and again. So for that, he/she wants to define a global variable in Laravel. Let’s see some of the best ways to define global variables in Laravel.

Define Global Variable In Laravel

There are many ways to define global variables in Laravel and it defer from developer to developer. Let’s see the best of them.

Table of Contents
1. Using Service Provider
2. Using Traits
3. Using Config File

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:


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:

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:


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



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:


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:


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:

  1. Laravel: Blade Switch Case Statement Example
  2. Laravel: Switch Case Statement In Controller Example
  3. Laravel: Change Column Type In Migration
  4. Laravel: Change Column Name In Migration
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Update Pivot Table In Laravel
  11. How To Install Vue In Laravel 8 Step By Step
  12. How To Handle Failed Jobs In Laravel
  13. How To Remove WooCommerce Data After Uninstall
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. Laravel Run Specific Migration
  18. How To Fix Elementor Icons Not Showing
  19. How To Schedule Tasks In Laravel With Example
  20. Warning: SPDX license identifier not provided in source file

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!


Leave a Comment