Laravel

Define global variables in laravel

Imagine you want to define some variables that can be accessed from anywhere in your laravel project. To achieve that, the best way will be to take advantage of laravel’s configuration file.

Creating a Configuration File

First, you need to create a file inside the config folder at the root of the laravel project – config/global.php. Inside the file, you need to return an array.

$my_config = array();
return $my_config;

 

Defining Variables

Once you have the configuration file ready, you can then define your global variables as key-value pairs inside the array. Remember, The array can also be multi-dimensional.

$my_config = array(
    'site_name' => "WickeDev",
    'site_desc' => "A blog for developers",
    'contact' => array (
        'email' => 'john.doe@website.com',
        'phone' => '+1-906-123-4567',
    )
);
return $my_config; 

 

Accessing Variables

Now, you can access the variables using “dot” syntax, including the configuration file name without the extension – php. You can do it in 2 ways.

1. Using the “Config” facade

Laravel has a built-in facade called Config. You can use the facade’s static get() method to access the variables like below.

$site_name = Config::get('global.site_name');
$email = Config::get('global.contact.email');

 

2. Using the “config()” function

The config() function works like the Config facade, just like below.

$site_name = config('global.site_name'); 
$email = config('global.contact.email');
Mohammad Zahed Kamal

View Comments

  • Wow das is Good, awesome blog layout! How long have you been posting for? you make blogging look easy. The overall look of your site is super-wonderful, as well as the content unit!

Share
Published by
Mohammad Zahed Kamal

Recent Posts

PHP to remove unnecessary key and value pairs from any multi-dimensional array

Today I will share a snippet I've used in a project. Using that function, you…

2 years ago

Use vanilla JavaScript to make Ajax request

JavaScript AJAX (Asynchronous JavaScript and XML) is a technique that gives the ability to send…

2 years ago

Add animation to bootstrap carousel elements

By default, Bootstrap carousel has no way to add animations to carousel elements. Here I'm…

2 years ago

Create custom pagination template in Laravel

Laravel comes up with a paginator that generates HTML compatible with the Tailwind CSS framework.…

2 years ago

Add Bootstrap Icons in SASS or SCSS

Bootstrap introduced their icons collection in November 2019 as Bootstrap Icons (v1.0.0-alpha). At that time,…

2 years ago

Create autocomplete using vanilla JavaScript

To create autocomplete feature for input field(s), HTML's datalist tag can be the easiest solution.…

2 years ago