Define Constant in Laravel

November 17, 2020

There are several ways to define constants in Laravel

Create constant.php inside the config folder and add the following code

<?php

return [
    'HTTPSTATUS' => [
        'Informational_Continue' => '200',
        'Success_OK' => '200',
        'Redirection_MovedPermanently' => '301',
        'ClientError_BadRequest' => '400',
        'ServerError_InternalServerError' => '500',
    ]
];

You can access the the constant with following code

 Config::get('constant.HTTPSTATUS.ClientError_BadRequest')

This is the other way to add the constant in Laravel

First, you can create the class with constant

namespace App;

class Constant {
   const API_KEY = '1234qeds';
}

Now you can add the alias to the config/app.php

'aliases' => [
  //...
  'Constant' => App\Constant::class,

You can use the following code now

Constant::API_KEY