In this post, I am going to explain “how to define a constant variable in Laravel”. we can create any type of constant variable like an array, String, Integer, etc.
And can access anywhere in application like view, Controller, middle-ware, etc.
Many times we require to define some global value for an application like user type, site URL, success message, error message, etc.
In this post, we will create one global config file and define all default variables with values in a created file. After that, we can use that variable from anywhere in a project.
Step 1:- Create Config File
first, we need to create a file in the config folder and then define constant variable and value in that file.
Create a global.php file in the config folder and paste the below code.
1 2 3 4 5 6 7 8 9 10 11 |
<?php return [ 'user_type' => ['Publisher', 'Admin'], 'success_msg' => "Record Inserted successfully", 'error_msg' => "Something went wrong" ] ?> |
Step:2 ) How to use Constant Variable, we can easily get config value using config() helper like:
1 2 3 4 5 |
$msg = config('global.success_msg'); $userType = config('global.user_type'); |
I hope you might have understood it properly, keep reading our other blog posts for more coding tricks.
Thanks!!
I’m a full-stack developer. My hobby and profession to write blog and programming tips that helps to others. I am a great admirer of PHP, Laravel, Codeigniter, AngularJS, Vue.js, Javascript, JQuery, WordPress, Plugin Development, Theme Development and Bootstrap from the early stage.