How to Define Global Variables in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Laravel is an awesome framework today, providing several good features, which is why it is a very popular PHP framework. When working on big website projects or ERP level projects, we need to define global variables like site title, pagination number, footer text, etc., depending on the project. In this tutorial, I will show you how to define and use global variables in Laravel, which provides a simple way to set global variables in our Laravel application with a good directory structure.

To define global variables, we need to create a global.php file in the config folder of your Laravel application. In this example, I have added three variables to the file: siteTitle, pagination, and tagLine, but you can add more. Once defined, you can access these global variables throughout the application, including in the controller, view, model, and anywhere else. Copy the code below and paste it into the global.php file.

config/global.php

return [

'siteTitle' => 'HD Site',

'pagination' => 5,

'tagLine' => 'Do the best'

];

After creating this file you can use using config() helper. in bellow line you can put anywhere and get "siteTitle" value, same way you can get other value too.

Example:

{{ config('global.siteTitle') }}

I hope it can help you...

Tags :
Shares