Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Mario
Mario

Posted on • Originally published atmariorodriguez.co on

     

How to Use Real Constants in Laravel

I’ve read several posts around the web suggesting the use of config variables as constants in Laravel. The issue I see with that, is that those are not real constants. They are variables. If you need to use real constants in Laravel, there are a couple of ways you can load your own constants. Let me show you how I get it done.

First, create a file calledconstants.php inside the bootstrap folder of your Laravel application. Define your constants in this file so they are all nice and cozy in one place. For example:

constants.php

<?phpdefine('COLOR_ONE', 'blue');define('COLOR_TWO', 'red');
Enter fullscreen modeExit fullscreen mode

Now, there are a couple of ways you can load this file so that the constants are available for use throughout your application. These are in no particular order. You can choose whichever method you prefer.

Method 1: autoload.php

Modify the filebootstrap/autoload.php by adding the following code at the end of it:

<?php//Load custom constants.require __DIR__.'/constants.php';
Enter fullscreen modeExit fullscreen mode

When you run your app, this line of code will load your bootstrap/constants.php file with all your constants as part of the Laravel bootstrapping sequence.

Method 2: composer.json

Alternatively, you can usecomposer.json to load the bootstrap/constants.php file by adding the following code to the “autoload” section, like so:

"autoload": {    "files": [        "bootstrap/constants.php"    ]}
Enter fullscreen modeExit fullscreen mode

Before this change can take effect, you must run the following command in Terminal to regenerate Laravel’s autoload files:

$ cd path/to/your/project$ composer dump-autoload
Enter fullscreen modeExit fullscreen mode

Once you run that command, your constants will be automatically loaded when you run your app.

That’s all there is to it. It’s not too difficult to define and load your own real constants in Laravel.

Was this post useful? Any issues or questions? Let me know onTwitter.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software engineer. Indie maker. Building https://fusioncast.fm
  • Location
    US
  • Joined

More fromMario

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp