Laravel - How to clear config:cache on each request - laravel

I am working on a project which will have 50 subdomains and I found a solution to load separate .env file based on a domain name and everything is working fine... now my problem is
I have to run command config:cache to clear the cache so sytem can load relevant .env file, otherwise, it keeps loading the older .env file. How can i ask system to do cache clear on each load in bootstrap/app.php file???
My Code to load .env files in bootstrap/app.php
$domain = '';
if(isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])){
$domain = $_SERVER['HTTP_HOST'];
}
if ($domain) {
$dotenv = \Dotenv\Dotenv::create(base_path(), '.env.'.$domain.'.env');
try {
$dotenv->overload();
} catch (\Dotenv\Exception\InvalidPathException $e) {
// No custom .env file found for this domain
}
}

I would advise against doing that because things WILL break.
However, to answer your question, you can use Artisan::call('config:clear') inside a middleware that you can call on each request.
But instead of doing that, you could build a middleware that detects the subdomain you're getting the request from and then call the command instead, just to avoid that extra load.

I used another way to solve this on my project. It is setting the config dynamically according to the request. The config is only valid for the current request. If the count of the dynamic config is less you can use
Config::set('myConfig.hostName', $hostName);
Before doing that you must use the package
use Illuminate\Support\Facades\Config;

Related

Laravel - Get current .env() Value

I am working on a Laravel project. I often change the database connection between Mysql and Sqlite during development. In a php artisan Laravel command I have an import routine. Because I don't want to write the data into the wrong database, I want to set an if condition before the import. But unfortunately it doesn't work quite as I imagined.
if ( env('DB_CONNECTION', null ) === 'sqlite') {
// Import to sqlite
} else if (env('DB_CONNECTION') === 'mysql') {
// Import to mysql
} else {
// no database in env DB_CONNECTION
}
In my .env file currrently the DB_CONNECTION is set on sqlite. But env('DB_CONNECTION', null) returns null.
What do I have to do to find out the current connection? Maybe using env() is not the right choice at this point?
For all those who will have the same problem in the future. Always! But really always, after you have modified the .env variable, you should execute the following "cleaning" commands:
php artisan config:cache
php artisan config:clear
If you still don't get a value, ask SO.
You should not use env() function anywhere except config files. Instead, use config('database.default'), because when configuration is cached, the env is empty for security reasons.
You may create multiple database connections in config/database.php and switch between them manually using facade: DB::connection('sqlite'), or DB::connection('mysql') and avoid this ugly if - else if tree.

Unable to boot ApiServiceProvider, configure an API domain or prefix in Laravel

I am using Laravel-8 as restful api. Also I am using Dingo Package. Initially the url was:
http://localhost:8888/myapp/server/public
And it was loading correctly.
However, I decided to remove public from the url. So I followed these steps:
Rename server.php in your Laravel root folder to index.php
Copy the .htaccess file from /public directory to your Laravel root folder.
When I tried to reload the url as:
http://localhost:8888/myapp/server
I got this error:
Unable to boot ApiServiceProvider, configure an API domain or prefix
C:\xampp\htdocs\myapp\server\vendor\dingo\api\src\Provider\DingoServiceProvider.php
protected function registerConfig()
{
$this->mergeConfigFrom(realpath(__DIR__.'/../../config/api.php'), 'api');
if (! $this->app->runningInConsole() && empty($this->config('prefix')) && empty($this->config('domain'))) {
throw new RuntimeException('Unable to boot ApiServiceProvider, configure an API domain or prefix.');
}
}
Even with:
http://localhost:8888/mygeapp/server/public/
The same error still applies
How do I resolve this?
Thanks
Please be sure to configure your IPI PREFIX in the env file
API_PREFIX=api

Laravel 5 url() doesn't contain scheme

I'm quite new in Laravel.
I'm working on an existing Laravel 5.8 project. I installed it locally with HomeStead.
I noticed a strange behaviour on redirects: considering my homepage is http://project.test/, when there is a redirection, say to /redirected, Laravel sets the location to http://project.test/://project.test/redirected! As I tried to figure out wat was going on, I saw that the url('/') Laravel function gives me ://project.test instead of http://project.test.
request()->getSchemeAndHttpHost() gives http://project.test.
Example in web.php:
Route::get('/info', function (Request $request) {
echo url('/'); // gives '://project.test'
echo '<br>';
echo request()->getSchemeAndHttpHost(); // gives 'http://project.test'
// This will lead me to 'http://project.test/://project.test/redirect'
// return redirect('/redirect');
});
I have the same problem with the static resources.
Config:
'url' => env('APP_URL', 'http://project.test') in config/app.php
APP_URL=http://project.test in the .env file.
I certainly missed something, but so far I couldn't find any information about this.
when you redirect check if you wrote : "Redirect::home()" , try "return Redirect::home()" (note the return)
I tested your routes, and it's working nicelly for me.
I give you my config,just replace "tlara" wich is my project name with your's : "project"
in host.sam
127.0.0.1 tlara.test #laragon magic! (note is not my ip 192.xx.xx, 127.0.0.1 is universal localhost)
in .env
APP_URL=http://localhost
..
REDIS_HOST=127.0.0.1 (i don't know if it is revelant)
..
SESSION_DOMAIN='localhost'
clear
clear caches (routes, caches, view) (may be useless)
test
tlara.test/info
127.0.0.1/info
localhost/tlara/public/info

What is difference between use env('APP_ENV'), config('app.env') or App::environment() to get app environment?

What is difference between use env('APP_ENV'), config('app.env') or App::environment() to get app environment?
I know that the env('APP_ENV') will to $_ENV, config('app.env') reads the configuration and App::environment() is an abstraction of all. And in my opinion the advantage is even this. Abstraction.
I do not know if there are other differences, such as the level of performance or security
In Short & up-to-date 2022:
use env() only in config files
use App::environment() for checking the environment (APP_ENV in .env).
use config('app.var') for all other env variables, ex: config('app.debug')
create own config files for your own ENV variables. Example:
In your .env:
MY_VALUE=foo
example config/myconfig.php
return [
'myvalue' => env('MY_VALUE', 'bar'), // 'bar' is default if MY_VALUE is missing in .env
];
Access in your code:
config('myconfig.myvalue') // will result in 'foo'
Explanation & History:
I just felt over it. When you cache your config file, env() will (sometimes?) not work right. So what I found out:
Laravel recommends only to use env() within the config files. Use the config() helper in your code instead of env(). For example you can call config('app.env') in your code.
When you use php artisan config:cache all the configuration strings are cached by the framework and any changes you make to your .env file will not be active until you run the php artisan config:cache command again.
From this article on Laracast:
UPDATE:
env() calls work as long as you don't use php artisan config:cache. So it's very dangerous because it will often work while development but will fail on production. See upgrade guide
Caching And Env
If you are using the config:cache command during deployment, you must
make sure that you are only calling the env function from within your
configuration files, and not from anywhere else in your application.
If you are calling env from within your application, it is strongly
recommended you add proper configuration values to your configuration
files and call env from that location instead, allowing you to convert
your env calls to config calls.
UPDATE Laravel 5.6:
Laravel now recommends in its documentation to use
$environment = App::environment();
// or check on an array of environments:
if (App::environment(['local', 'staging'])) {
// The environment is either local OR staging...
}
and describes that env() is just to retrieve values from .env in config files, like config('app.env') or config('app.debug').
You have two equally good options
if (\App::environment('production')) {...}
or
if (app()->environment('production')) {...}
app()->environment() is actually used by Bugsnag, look in documentation here it says
By default, we’ll automatically detect the app environment by calling the environment() function on Laravel’s application instance.
Now, differences:
1) env(...) function returns null after caching config. It happens on production a lot.
2) you can change config parameters inside unit tests, it gives you flexibility while testing.
One thing to consider is perhaps the convenience factor of passing string to app()->environment() in order validate your current environment.
// or App:: whichever you prefer.
if (app()->environment('local', 'staging')) {
logger("We are not live yet!");
Seeder::seedThemAll();
} else {
logger("We are LIVE!");
}
2023 Updated Answer
env() helper works when there is no config.php inside bootstrap/cache directory
config() helper works both in case if the file config.php is present or not. If the file is not present then if will parse the variables at runtime, but if it does find one; it uses the cached version instead.
In production environment the artisan commands we run to add/remove the config file.php becomes of paramount importance in context of how env() and config() behave.
Consider the following example to understand the concept:
Route::get('/', function () {
// to experiment: set APP_ENV=production in your .env file
echo 'Via env(): ' . env('APP_ENV') . '<br/>'; // production
echo 'Via config(): ' . config('app.env'); // production
/*
|--------------------------------------------------------------------------
| run: php artisan config:cache
|--------------------------------------------------------------------------
|
| The config:cache command will generate a configuration cache file (config.php) in the bootstrap/cache directory.
| At this point, the env() helper will no longer work as all ENV variables will be flushed in favor of the cached config.php file.
|
*/
echo '<hr/>';
echo 'Via env(): ' . env('APP_ENV') . '<br/>'; // null
echo 'Via config(): ' . config('app.env'); // production
/*
|--------------------------------------------------------------------------
| run: php artisan config:clear
|--------------------------------------------------------------------------
|
| The config:clear command will remove (config.php) configuration cache file from the bootstrap/cache directory.
| At this point, the env() helper will work again as framework doesn't find a cached configuration file.
|
*/
echo '<hr/>';
echo 'Via env(): ' . env('APP_ENV') . '<br/>'; // production
echo 'Via config(): ' . config('app.env'); // production
});
So general rule of thumb is to always use config() helper inside your code files; in this way your code does not explode if cached configuration file is available or not.
Now getting the environment is so important and common; Laravel gives us a handful ways we can accomplish the same:
// APP_ENV=production inside .env file
App::environment(); // production
app()->environment(); // production
App::environment('production'); // returns boolean: true
app()->environment('production'); // return boolean: true
Keep in mind you are using App facade or app() helper they all will be using config helper under the hood.
If you are using the config:cache command during deployment, you must make sure that you are only calling the env function from within your configuration files, and not from anywhere else in your application.
If you are calling env from within your application, it is strongly recommended you add proper configuration values to your configuration files and call env from that location instead, allowing you to convert your env calls to config calls.
Add an env configuration option to your app.php configuration file that looks like the following:
'env' => env('APP_ENV', 'production'),
More: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0
In 12factor methodology application contains two types of configuration values:
internal which not vary between deploys and are stored in laravel ./config/ folder. In this type we usually store some technical optimal/good values used in application which should not be changed by users over time e.g. optimal image compression level, connection timeout, session expiration time etc.
external which vary between deploys and are stored in .env file (but should not be stored in git repo, however .env.example with example values with detail info can be stored in repo). In this type we store usually some important/protected values which depends on local environment e.g. passwords, debug mode, db address etc.
Laravel proposes handy approach for this
in regular code we use only config(...) helper (so on this level programmer do not need to know which configuration value is internal and which is external)
in configuration code external config values should be set using env(...) helper e.g. in config/app.php 'debug' => env('APP_DEBUG', false)

Unable to get laravel/database and restler working with versioning

I have an existing website up and running, and now I want to add a REST interface to it in an api subdirectory. I'm not able to get this to work with versioning. I installed like so (no errors):
$ php ~/bin/composer.phar create-project laravel/database --prefer-dist api
$ cd api
$ php ~/bin/composer.phar require restler/framework 3.0.0-RC6
Then I uncommented the lines in public/index.php related to Restler and add a new API class that just echos a string. If I run this via php artisan serve and look at it through the localhost URL, then the method works.
Now I want to enable versioning, so I added these lines to public/index.php
use Luracast\Restler\Defaults;
Defaults::$useUrlBasedVersioning = true;
And in app/controllers I created a v1 directory and moved Test.php into that. I also added a namespace directive to the file of the format namespace A\B\v1
When I restart the artisan server and query the API, I get a 404 error. I've tried as both http://localhost:8000/Test and http://localhost:8000/v1/Test
What have I forgotten to do?
Here is how I made it to work. Note the folder where I placed the api class file.
in index.php
use Luracast\Restler\Restler;
use Luracast\Restler\Defaults;
Defaults::$useUrlBasedVersioning = true;
$r = new Restler();
$r->addAPIClass('A\B\Test');
Test.php kept in app/controllers/A/B/v1/Test.php
<?php namespace A\B\v1;
class Test
{
public function get()
{
return 'working';
}
}
Both http://localhost:8000/v1/test and http://localhost:8000/test return "working"

Resources