Define Global Variable in Laravel 5.8 (ok)

https://www.itsolutionstuff.com/post/define-global-variable-in-laravel-58example.html

C:\xampp\htdocs\reset\config\global.php

<?php
return [
  'pagination_records' => 10,
  'user_type'          => ['User', 'Admin'],
]
?>

C:\xampp\htdocs\reset\routes\web.php

<?php
use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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');
});
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::get('get-user-type', function () {
  dd(config('global.user_type'));
});

Define Global Variable in Laravel 5.8

By Hardik Savani July 31, 2019 Category : LaravelPlayUnmuteLoaded: 1.20%FullscreenVDO.AI

In this tutorial, we will learn how to define global variable in laravel 5.8 application. you can define constants variable with string value, integer value, array value and you can access for all controller, all views, all blade files, middleware too in laravel 5.8 using config.

We must be require to define some global value for application like number of pagination records, user type, site url etc. if you are working with small project then i will suggest to create global config file for define constants variable.

In this example we will create one global config file will all define default variable with values. so you can use that variable from anywhere in project. you can also check bellow screen shot for file location.

Create Global Config File

We need to create global.php config file with constants variable value and you can also define array value like as bellow:

config/global.php

<?php   return [      'pagination_records' => 10,      'user_type' => ['User', 'Admin'],]  ?>

Use Global Variable

You can easily get value using config() helper. you can see bellow example:

routes/web.php

Route::get('get-user-type', function(){    dd(config('global.user_type'));});

Read Also: Laravel 5.8 User Roles and Permissions Tutorial

Route::get('get-user-type', function(){    dd(config('global.pagination_records'));});

I hope it can help you....

Last updated

Was this helpful?