megacolorboy

Back

Published on November 7th, 2020

Laravel

Create aliased class constants in Laravel

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:Next, create a file named in the directory and copy-paste the following code:Then, go to the file and define your new alias:Lastly, execute the following commands to update your app's configuration:After that, you can use your new constants anywhere (Controllers, Models or Blades) like this:Learning this new technique helps me keep the code clean and makes it easier to trace the constants.Hope you find this tip useful!

1 minute read

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:


'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!