There are many ways to define constants in Laravel but I learnt a neat technique where you can define constants using an alias.
First off, create the following directory:
mkdir app/Constants
Next, create a file named MyConstants.php
in the app/Constants
directory and copy-paste the following code:
<?php
namespace App\Constants;
class MyConstants {
const HELLO = 'hello';
}
?>
Then, go to the config/app.php
file and define your new alias:
<?php
'aliases' => [
// previously defined aliases...
'MyConstants' => App\Constants\MyConstants::class,
]
?>
Lastly, execute the following commands to update your app's configuration:
php artisan config:clear
composer dump-autoload
php artisan config:cache
After that, you can use your new constants anywhere (Controllers, Models or Blades) like this:
<?php
echo MyConstants::HELLO;
?>
Learning this new technique helps me keep the code clean and makes it easier to trace the constants.
Hope you find this tip useful!