How to Define Constant Variable in Laravel - TechvBlogs

How to Define Constant Variable in Laravel

In this article, You will learn How to Define Constant Variables in Laravel.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

1 year ago

TechvBlogs - Google News

As you may already be aware, the popularity of the Laravel framework is growing as a result of its practical features and myriad time-saving tricks.

Building global variables that can be utilized across your project is frequently important. For example, you may specify them in a single file and use them everywhere you need them instead of manually passing them if you are working in the admin section and need to submit one record per page to paginate() method to expose on record at a time everywhere you go.

There is a method for defining constants in a .env file that we are familiar with, but is there another choice, such as putting all constants in a constant file? If you use constants frequently and most of them are used throughout the program, you should keep them in a global.php file. For this method, just create a file called global.php in the config directory. An array of configuration values from the file must be returned.

How to Define Constant Variables in Laravel

1. Create a config file

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

config/global.php

<?php
   
return [
  'pagination'=>[
     'perPage'=>25
  ]
]
  
?>

2. Use Constant Variable

You can easily get value using config() helper. you can see this in the example:

<?php

Route::get('/users', function(){

    return config('global.pagination.perPage');
});

Thank you for reading this article.

Read Also: How to get the raw SQL query from the Laravel Query Builder

If you want to manage your VPS / VM Server without touching the command line go and  Checkout this linkServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a  matter of minutes.  You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.

Comments (0)

Comment


Note: All Input Fields are required.