SwiftD
SwiftD

Reputation: 6069

Storing and retrieving constants in laravel

I have just started playing with laravel haveing come from codeigniter and I am trying to work out the best way to define a series of constants. CI uses a constants folder under app/config and I was largely happy with this approach for most things but wanted advice as to the best way to do this in Laravel.

My constants fall into 3 categories and I would like advice if possible on how best to store and retrieve each (baring in mind I'm completely new to Laravel.

Type 1: Constants which need to be loaded everytime a controller is called: e.g. I would like to start by defining a constant to tell me if the user is requesting content via ajax, this is what I used to do in CI constants file: define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')

Type 2: Constants which can be changed by the user: Are these best stored in a database or would writing to a config file be a better option? Again looking for advice on how to store and retrieve

Type 3: Constants which are only needed in specific controllers: Ideally I would like to be able to group constants into arrays or separate files and pull them out in groups as required. e.g. I could just retrieve my upload settings for my upload controller.

Thanks for any help/advice in advance - examples would be greatly appreciated

Upvotes: 4

Views: 8895

Answers (3)

Khang Doan
Khang Doan

Reputation: 436

<?php
//file : app/config/constants.php

return [
    'IS_AJAX' => isset($_SERVER['HTTP_X_REQUESTED_WITH']
];

in anywhere:

echo Config::get('constants.IS_AJAX');

Upvotes: 0

Sebastian Gomez
Sebastian Gomez

Reputation: 704

My solution is create a file inside app/config folder called "constants.php" app/config/constants.php

The code inside is in array way.

"some value", 'c2'=>"some value" ); ?>

then inside each controller you can retrieve using Config::get('constants.c1');

I think is an easy way to do it, it's more scalable.

Upvotes: 0

crynobone
crynobone

Reputation: 1814

Type 1 You can add any constant in Bundle (or application) start.php file.

Type 2 and 3 I would suggest using Config for both these requirement.

Upvotes: 8

Related Questions