5

In my config/app.php file, I have added some variable and I have used these variable in my controller and view files. See below variables:

'META_TITLE' => 'title'
'META_KEYWORDS' => 'keyword'
'META_DESCRIPTION' => 'description'

and I have used these variables like this Config::get("app.META_TITLE")

But I want to override those variable in any of my controller as per requirement.

okconfused
  • 3,567
  • 4
  • 25
  • 38

3 Answers3

4

Laravel stores all the config file values into one single array. So, the "Laravel way" of overwriting the config variables after they are set is to edit the array in which they are stored:

config([

    // overwriting values set in config/app.php
    'app.META_TITLE'       => 'new meta title',
    'app.META_KEYWORDS'    => 'new meta keywords',
    'app.META_DESCRIPTION' => 'new meta description',

    // in case you would like to overwrite values inside config/services.php
    'services.facebook.client_id'     => 'client id',
    'services.facebook.client_secret' => 'client secret',

]); 

With this concept you can edit any variable set in any config file - just specify which config file they are stored in.

Chris
  • 3,311
  • 4
  • 20
  • 34
4

For Laravel 5.1, from the docs (also works in 5.8)

To set configuration values at runtime, pass an array to the config helper:

config(['app.timezone' => 'America/Chicago']);

But note that if you want to override environment variables in Dusk, this approach helps: https://laracasts.com/discuss/channels/testing/how-to-change-env-variable-config-in-dusk-test?page=1#reply=475548

Ryan
  • 22,332
  • 31
  • 176
  • 357
  • Unfortunately I'm now having problems with the Dusk hack in 5.8+, hence a new question: https://stackoverflow.com/q/58450836/470749 – Ryan Oct 18 '19 at 12:23
3

It sounds like a simple check to see if the value needs to be overridden.

In the controller:

$title = Config::get("app.META_TITLE");

if ($titleOverrideValue) {
    $title = $titleOverrideValue;
}

Or, to put it in a shorter way:

$title = $titleOverrideValue ?: Config::get("app.META_TITLE");
Kryten
  • 15,230
  • 6
  • 45
  • 68