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:
<?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:
- Laravel: Blade Switch Case Statement Example
- Laravel: Switch Case Statement In Controller Example
- Laravel: Change Column Type In Migration
- Laravel: Change Column Name In Migration
- How To Use Where Date Between In Laravel
- How To Add Laravel Next Prev Pagination
- Laravel Remove Column From Table In Migration
- Laravel: Get Month Name From Date
- Laravel: Increase Quantity If Product Already Exists In Cart
- How To Update Pivot Table In Laravel
- How To Install Vue In Laravel 8 Step By Step
- How To Handle Failed Jobs In Laravel
- How To Remove WooCommerce Data After Uninstall
- How To Get Latest Records In Laravel
- How To Break Nested Loops In PHP Or Laravel
- How To Pass Laravel URL Parameter
- Laravel Run Specific Migration
- How To Fix Elementor Icons Not Showing
- How To Schedule Tasks In Laravel With Example
- 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!